class Cat(object): def __init__(self, hungry=False): self.hungry = hungry def should_we_feed_the_cat(self): if self.hungry: print("Yes") else: print("No")
Let's initialize a cat
>>> felix = Cat(True) >>> felix.should_we_feed_the_cat() Yes
First, we should clarify the difference between a function and a method. A method is a function which is associated with an object. So all the functions we defined within our class above are associated with an object of that class and hence they are methods. However, we can still call methods as function
>>> type(Cat.should_we_feed_the_cat) <class 'function'> >>> type(felix.should_we_feed_the_cat) <class 'method'>
Cat.should_we_feed_the_cat(felix)
felix.should_we_feed_the_cat()
If we get this wrong and for example call the method by passing in the object, we will get an error message which you probably have seen before (I certainly have)
>>> felix.should_we_feed_the_cat(felix) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: should_we_feed_the_cat() takes 1 positional argument but 2
were given
If you really want to avoid the self variable you can do that by using the @staticmethod decorator
class Cat(object): def __init__(self, hungry=False): self.hungry = hungry @staticmethod def other_function(): print("This function has no self variable")
class Cat(object): def __init__(whatever, hungry=False): whatever.hungry = hungry def should_we_feed_the_cat(whatever): if whatever.hungry: print("Yes") else: print("No")
Given the very simple concept captured by the self variable, you might already think about ways to get rid of it and use other ways to access the class attribute. If you have experience with other programming languages like Java, you might prefer to just have a pre-defined keyword. However, that does not seem to be an option in Python. If you are interested, here is a blog post by Guido Van Rossum arguing for keeping the explicit self variable.
I hope that was useful and let me know if you have questions/comments in the comments section below.
cheers
Florian
Florian
Hi Florian, excellent post!
ReplyDelete