Let’s say we have this code:
class C(CC):
a = 1
b = 2
def __init__(self):
self.x = None
self.y = 1
How can I quickly find out in Python where is the attribute or method defined? If it belongs to ancestor class or if it’s the method of class C. You can see attributes a, b, x, y . Must they belong to class C? or can they be from ancestor classes? When does the type is assigned to the variable?
Why not rather use
class C(CC):
a = 1
b = 2
x = None
y = 1
thank you
In the first example,
aandbare attributes of the C class object. (Think “static” attributes.) Andxandyare attributes of C instances. (So, regular instance attributes.)In the second example, all four are attributes of C, not of its instances.
In Python, you can’t “declare” attributes as defined by a specific class, which means there are no attribute definitions to inherit to begin with. (More or less, but I’m not going to muddle the waters by introducing
__slots__). You can find method definitions by searching for “def method_name(“, and method definitions are inherited as in most OO languages.Confusingly, you can access class attributes through instances of a class, then if you assign a new value to that attribute, a new instance attribute is created:
Which does let you give instance attribute default values by using class attributes. I don’t believe this is a very common thing to do though – I favour using default values to
__init__()arguments.