So what's going on here is that the f method belongs to the parent class, and is correctly inherited by the child class. The f field, however, belongs to an instance of the child class, not the class itself, and therefore masks the method. I'm not sure what you're actually trying to achieve, as if you'd like to have a string in your child class that doesn't override the parent, its probably best just to give it another name. You can get the result you're expecting by having an instance field holding the method though:
class Parent():
def __init__(self):
self.f = self.method
def method(self):
print("in a method")
class Child(Parent):
def __init__(self):
self.f = "not a method"
super().__init__()
c = Child()
c.f()
in a method
This is a bit confusing when you start out, as it feels like methods annotated with @classmethod should beling to the class, and those not annotated should belong to the instance. In practice, however, that would mean a copy of every method would have to reside with every instance, which would be terrible wasteful. In fact, the @classmethod annotation just means that the method is called with the class a the first parameter not the instance.
Also just as an aside, there is a style standard for python called PEP8 and that says that classes should have capital letters, it doesn't make your code work any differently though.
So what's going on here is that the
fmethod belongs to theparentclass, and is correctly inherited by thechildclass. Theffield, however, belongs to an instance of thechildclass, not the class itself, and therefore masks the method. I'm not sure what you're actually trying to achieve, as if you'd like to have a string in your child class that doesn't override the parent, its probably best just to give it another name. You can get the result you're expecting by having an instance field holding the method though:This is a bit confusing when you start out, as it feels like methods annotated with
@classmethodshould beling to the class, and those not annotated should belong to the instance. In practice, however, that would mean a copy of every method would have to reside with every instance, which would be terrible wasteful. In fact, the@classmethodannotation just means that the method is called with the class a the first parameter not the instance.Also just as an aside, there is a style standard for python called PEP8 and that says that classes should have capital letters, it doesn't make your code work any differently though.
I hope that helps!
Thank you! :)