I would like to use a class attribute as a default value for one of the arguments to my class's __init__
method. This construct raises a NameError
exception, though, and I don't understand why:
class MyClass(): __DefaultName = 'DefaultName' def __init__(self, name = MyClass.__DefaultName): self.name = name
Why does this fail, and is there a way to do this that works?
Instance attributes are for data specific for each instance and class attributes supposed to be used by all instances of the class. "Instance methods" is a specific class attributes which accept instance of class as first attribute and suppose to manipulate with that instance.
Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor. Defined directly inside a class.
Instance variables have scope only within a particular class/object and are always assosiated with a particular class. Attributes are meant to be used as messages on a notice board so that classes the have access to a particular request, page, session or application can usethem.
All classes in Python are objects of the type class, and this type class is called Metaclass . Each class in Python, by default, inherits from the object base class.
That's because, according to the documentation:
Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined
When __init__()
is defined, the definition of MyClass
is incomplete, as it's still being parsed, so you can't refer to MyClass.__DefaultName
yet. One way to work around that is to pass a special unique value to __init__()
, such as None
:
def __init__(self, name=None): if name is None: name = MyClass.__DefaultName # ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With