calling a function in python got nothing instead [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I got a code like this.
....
class SocketWatcher(Thread):
....
def run(self):
....
TicketCounter.increment() # I try to get this function
...
....
class TicketCounter(Thread):
....
def increment(self):
...
when I run the program I got this error.
TypeError: unbound method increment() must be called with TicketCounter instance as first argument (got nothing instead)
i there any way that I can call the increment() function from TicketCounter Class to the SocketWatcher Class? or Does my calling is wrong...

You must create an instance of the class TicketCounter first before you can call any functions from it:
class SocketWatcher(Thread):
....
def run(self):
....
myinstance = TicketCounter()
myinstance.increment()
Otherwise the method is not bound anywhere. Creating an instance binds the method to the instance.

Member functions are part of the instances of a Class. So whenever you want to call you must always call it with an instance of the Class and not the Class name itself.
You could do:
TicketCounter().increment()
What this does is that it initialises an object and then calls this function. The following example will make it clear.
class Ticket:
def __init__(self):
print 'Object has been initialised'
def counter(self):
print "The function counter has been invoked"
And the output to illustrate this:
>>> Ticket().counter()
Object has been initialised
The function counter has been invoked
>>>

You are passing self, so I'm assuming that you need to create an instance. But if the method really doesn't need an instance then you can use the #classmethod or #staticmethod decorators and your code would work:
class TicketCounter(Thread):
#classmethod
def increment(cls):
...
or
class TicketCounter(Thread):
#staticmethod
def increment():
...
both can be called as TicketCounter.increment()

Related

How to use any obtained variable from a function in other functions in Python classes? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 21 days ago.
Improve this question
I am trying to use one variable obtained from one function in other function. However , it gives error. Let me explain it wih my code.
class Uygulama(object):
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0",
retry=3)
#There are unrelated codes here
def gateway_find(self):
#Find ip any range in which you conncet:
self.ip_range=conf.route.route("0.0.0.0")[1]
self.ip_range1=self.ip_range.rpartition(".")[0]
self.ip_range2=self.iprange_1+".0/24"
When , run the foregoing codes , i get this error AttributeError: 'Uygulama' object has no attribute 'ip_range2'
How can i use such variable which are obtained from other function in the other function. How can i fix my problem ?
Call order of init functions
Place function that define attribute first
In the __init__ function, you call refresh, who use (need) ip_range2 before gateway_find who create the attribute and set a value to it. Swap the two lines, you should be fine.
def __init__(self):
self.araclar()
self.gateway_find() # gateway_find will set the ip_range attribute
self.refresh() # So refresh function will be able to access it
Usually, we place init functions first, then function that will call post-init processes like refresh.
Class attribute default value
Alternatively, you can define a default value for ip_range2 like this:
class Uygulama(object):
ip_range2 = None
def __init__(self):
self.araclar()
self.refresh()
self.gateway_find()
def refresh(self):
self.a, self.b = srp(Ether(dst="FF:FF:FF:FF:FF:FF") / ARP(pdst=self.ip_range2), timeout=2, iface="eth0", retry=3)
Be aware that such default value is shared with all other instances of the class if not redefined in __init__, so if it's a mutable (like a list), it might create really weird bugs.
Usually, prefer defining value in the __init__ like you do with the gateway fct.
That error explains correctly that you do not have a class attribute called ip_range2. You need to define the class attribute first.
class Uygulama(object):
ip_range2 = ''
...
then use that with self.ip_range2.

"AttributeError: 'NoneType' object has no attribute" when creating class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have defined a simple class but recieve the error AttributeError: 'NoneType' object has no attribute 'bar' when trying to use it. What am I doing wrong?
def Foo():
a = 0
def bar(self):
return self.a
f = Foo()
f.bar() # error
This is the syntax to define a function
def Foo():
to define a class you'd say
class Foo:
Your problem
Foo is defined with def, which makes it a function, not a class. If you want Foo to contain functions, then it needs to be a class.
Solution
Use the class keyword to turn Foo into a class:
class Foo():
If you're trying to create a class, try :
class Foo:
def bar(self):
return self.a
class Foo():
a = 0
def bar(self):
return self.a
f = Foo()
f.bar()

Python, involving defining a class [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have this problem I am trying to solve:
Write the definition of a class ContestResult containing:
•An instance variable winner of type String , initialized to the empty String.
•An instance variable second_place of type String , initialized to the empty String.
•An instance variable third_place of type String , initialized to the empty String.
•A method called set_winner that has one parameter, whose value it assigns to the instance variable winner .
•A method called set_second_place that has one parameter, whose value it assigns to the instance variable second_place .
•A method called set_third_place that has one parameter, whose value it assigns to the instance variable third_place .
•A method called get_winner that has no parameters and that returns the value of the instance variable winner .
•A method called get_second_place that has no parameters and that returns the value of the instance variable second_place .
•A method called get_third_place that has no parameters and that returns the value of the instance variable third_place .
This is my code:
class ContestResult():
def __init__(self):
self.winner= ""
self.second_place= ""
self.third_place= ""
def set_winner(self,value):
self.winner= value.set_winner
def set_second_place(self,value):
self.second_place= value_set_second_place
def set_third_place(self,value):
self.third_place= value.set_third_place
def get_winner(self):
return self.winner
def get_second_place(self):
return self.second_place
def get_third_place(self):
return self.third_place
I am receiving this error:
Exception occurred(<class 'AttributeError'>, AttributeError("'str' object has no attribute 'set_winner'",)
Can someone help me with this? Please and thank you.
One are passing in a string to set_winner. That is why you're seeing the error.
However, you don't need to create the set_winner and get_winner functions in Python. All of the object's member variables, in this case winner, second_place and third_place, are publicly accessible. If you really want to have mutators and accessors, the Pythonic way of doing so is with property:
class ContestResult(object):
def __init__(self):
self.__winner = ''
#property
def winner(self):
return self.__winner
#winner.setter
def winner(self, value):
print "I'm about to set the value of winner"
self.__winner = value
and now when you want to see the "winner" property:
foo = ContestResult()
foo.winner = "Frank"
it works just like a regular member variable.
in def set_winner(self,value), presumably value is a string, right? Why are you calling value.set_winner?
self.winner = value
Note that this is true for all your set_s.
You really don't need all that with Python unless you're trying to modify the way attributes are actually get and set.
class ContestResult(object):
def __init__(self, winner, second_place, third_place):
self.winner = winner
self.second_place = second_place
self.third_place = third_place
Stick = ContestResult("Foo", "Bar", "Eggs")
Stick.second_place #gets "Bar"
Stick.winner = "Clown" #sets Stick.winner
Python isn't Java :) you don't need those methods -- again, unless you're going to be modifying the data or decorate the method or something. In which case you can use the #property syntax as outlined by wheaties -- and in doing so, you still don't actually call the get or set methods, you just interact in a Pythonic way and use assignment.
Stick.second_place = "Earl" #this will call the property setter

how to return a function in a different class in python 3.3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I know this is a really bad description but how can i get this to work:
class Test1():
def test_p1():
print("This is part 1 of Test1")
def Test2():
return test_p1()
Thanks in advance!
Well, there are several options.
The most basic are:
Create instance first
class Test1():
def test_p1(self):
print("This is part 1 of Test1")
def Test2():
return Test1().test_p1()
However, you should use it when having new instance makes sense (depends on your API).
Make it class method
class Test1():
#classmethod
def test_p1(cls):
print("This is part 1 of Test1")
def Test2():
return Test1.test_p1()
Make it static method (discouraged)
class Test1():
#staticmethod
def test_p1():
print("This is part 1 of Test1")
def Test2():
return Test1.test_p1()
Alternative: use inheritance
In some cases (maybe it is your case too, we do not know) it makes sense to actually utilize inheritance: create a class that will inherit from Test1. This way you can override parts of it and refer to parent methods. Example:
class Test1():
def test_p1(self):
print("This is part 1 of Test1")
class SomeOtherClass(Test1):
def test2(self):
return super(SomeOtherClass, self).test_p1()
and then use it like this:
my_instance = SomeOtherClass()
result = my_instance.test2()
But again, it really depends on your API / library.
Alternative 2: module-level function
User #user2357112 correctly pointed out, that module-level function can be even better (simpler) idea:
def test_p1():
print("This is part 1 of Test1")
def Test2():
return test_p1()
Side note: PEP8
To avoid confusion, as Python is really dynamic, you should give a "hint" to developers on what they are using, and in general follow coding style defined in PEP8:
module names are all_lower_case,
functions and methods are also all_lower_case,
classes are CamelCase (same applies to factory-like functions returning class instances),
constants are ALL_UPPER_CASE,
object properies are all_lower_case,
(and many more - the above is only about non-confusing naming)
Tadeck gave a detailed answer while I was typing mine, but here is my initial solution to what I believe you are trying to accomplish. I'm adding my input simply because I'm new to Python and I think a beginner's perspective may be beneficial for OP.
class Test1():
def test_p1(self):
print "This is part 1 of Test1"
def Test2():
myTest = Test1()
return myTest.test_p1()
Test2()
In your original code you attempt to call the test_p1 method without ever instantiating the Test1 class. So I did that first, myTest = Test1(), and then called the test_p1() method using my newly created myTest object.
Also, I added self to the argument list in the test_p1 method. I don't exactly understand why but apparently the lack of self makes it an unbound method which causes some problems.
You have to specify the class containing the functin. Call Test1.test_p1().
(Works in python3, but not in 2.x as there is this fuzz about bound and unbound thingies.)
Maybe you would want to use capital letters for classes and minuscules for functions.
A more common case is the following:
You have a class that defines methods:
class Animal:
def bark (self): print ('woof')
Then somewhere else you instantiate an object of this class and then invoke the method of the instance:
spike = Animal ()
spike.bark ()

Import class in same file in Python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm new to python and I have a file with several classes. In a method in the class "class1" I want to use a method from another class "class2". How do I do the import and how do I call the method from class1? I have tried several different things but nothing seems to work.
You don't need to import them, because they are already in the same file.
Instead, do something like this:
class1 = Class1() #assigns class1 to your first class
Then call a method inside of Class1 like this:
Class2():
def method2(self):
class1.method1() #call your method from class2
Basically you are taking Class2() and pointing it to the instance class2, then you are calling a method of that class by doing class2.method2(). It's just like calling a function from the current class, but you use instance name in front of it.
Here is an example:
class Class1():
def method1(self):
print "hello"
class Class2():
def method2(self)
class1 = Class1()
class1.method1()
Then, when you call Class2() it will print 'hello'.
Let's say your file with all the classes is called myclass.py with the following:
class Class2(object):
def foo(self):
return 'cabbage'
class Class1(Class2):
def bar(self):
return self.foo()
In your main script, you can import the module as usual:
import myclass
And now you can create an instance of class1:
myinstance = myclass.Class1()
Then you can call the function directly:
myinstance.bar()
# Returns 'cabbage'
If all of the classes are in the same file, you don't need to import them. They are in the module scope already. Here's an example:
class A():
def print_one(self):
print "one"
class B():
def print_two_and_one(self):
print "two"
A().print_one()
B().print_two_and_one()

Categories

Resources