Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a class attribute as a default value for an instance method?

Tags:

python

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?

like image 638
manniongeo Avatar asked Oct 28 '10 09:10

manniongeo


People also ask

Can a class contain instance attributes and instance methods?

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.

What is difference between class attribute and instance attribute?

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.

Are attributes and instance variables the same?

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.

What is the default class in Python?

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.


1 Answers

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     # ... 
like image 124
Frédéric Hamidi Avatar answered Sep 24 '22 02:09

Frédéric Hamidi