In Python, I am able to access the non-predefined class variables both from the class as well as instances. However, I am not able to access the predefined class variables (such as "name") from the object instances. What am I missing? Thanks.
Here is a test program that I wrote.
class Test:
'''
This is a test class to understand why we can't access predefined class variables
like __name__, __module__ etc from an instance of the class while still able
to access the non-predefined class variables from instances
'''
PI_VALUE = 3.14 #This is a non-predefined class variable
# the constructor of the class
def __init__(self, arg1):
self.value = arg1
def print_value(self):
print self.value
an_object = Test("Hello")
an_object.print_value()
print Test.PI_VALUE # print the class variable PI_VALUE from an instance of the class
print an_object.PI_VALUE # print the class variable PI_VALUE from the class
print Test.__name__ # print pre-defined class variable __name__ from the class
print an_object.__name__ #print the pre-defined class varible __name__ from an instance of the class
That's normal. Instances of a class look in that class's __dict__ for attribute resolution, as well as the __dict__s of all ancestors, but not all attributes of a class come from its __dict__.
In particular, Test's __name__ is held in a field in the C struct representing the class, rather than in the class's __dict__, and the attribute is found through a __name__ descriptor in type.__dict__. Instances of Test don't look at this for attribute lookup.
I don't have a great answer for "why". But here's how you can get to them, using __class__:
>>> class Foo(object): pass
...
>>> foo = Foo()
>>> foo.__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__name__'
>>> foo.__class__.__name__
'Foo'
>>>
Related
I want to create a baseclass that has an attribute which should not change. Any derived class from this baseclass should have this attribute aswell. My idea was:
class baseclass(object):
flag = "some attr for all classes"
def __init__(self, baseattr):
self.baseattr = baseattr
class child(baseclass):
def __init__(self, baseattr, childattr):
super(child, self).__init__(baseattr)
self.childattr = childattr
My thinking was, if I know look at child.__dict__:
print(child.__dict__["flag"])
it should return "special attribute ... baseclass" but instead I get a KeyError:
Traceback (most recent call last):
File "./test.py", line 14, in <module>
print(child.__dict__["flag"])
KeyError: 'flag'
while when calling baseclass.__dict__['flag']
everything is fine. Is there a way to set flags for all derived class that inherit from baseclass?
First of all, I think it would be nice if you could review the concepts related to a Class definition so you can understand the difference between a class instance and a class object.
Overall, the __dict__ that you're trying to access implements the object namespace. It was not suppose to be accessed directly as you're trying to do. But for the sake of understanding I'll use it to illustrate the class instance vs class object difference.
Calling __dict__ as you were will get you the dict containing the attributes of your child class object (the default ones and the ones you defined in your Class definition):
>>> child.dict
dict_proxy({'module': 'main', 'doc': None, 'init': })
However, when you decided to put flag in your baseclass like you did, you were defining it as a part of your baseclass class object. It is not declared each time for instance, it was declared once you imported your class definition. Therefore, you can see flag if you do:
>>> baseclass.dict
dict_proxy({'module': 'main', 'flag': 'some attr for all classes', 'dict': , 'weakref': , 'doc': None, 'init': })
Finally, if you access an object instance __dict__ you'll see the attributes you declared with self (including baseattr that was declared when you called super):
>>> child('some base attr', 'some child attr').dict
{'childattr': 'some child attr', 'baseattr': 'some base attr'}
That being said, you already have to access to flag from any object instance. Being more specific, you have access to every attribute defined in the class definition, the inherit class definition and in your instance. So I really recommend you stop using __dict__ and access things the way they were intended to:
>>> your_obj_instance = child('some base attr', 'some child attr')
>>> your_obj_instance.childattr
'some child attr'
>>> your_obj_instance.baseattr
'some base attr'
>>> your_obj_instance.flag
'some attr for all classes'
I'm trying to understand if there are differences between self and cls but I'm struggling, even though a lot of discussion on this topic exists. For instance:
class maclass():
A = "class method"
def __init__(self):
self.B = "instance method"
def getA_s(self):
print(self.A)
def getA_c(cls):
print(cls.A)
def getB_s(self):
print(self.B)
def getB_c(cls):
print(cls.B)
C = maclass()
C.getA_s()
C.getA_c()
C.getB_s()
C.getB_c()
which give me:
class method
class method
instance method
instance method
So whether I use self or cls, it always refers to the same variable. When I add a self.A in the Init__, the cls.A is just replaced
def __init__(self):
self.B = "instance method"
self.A = "new instance method"
and I get:
new instance method
new instance method
instance method
instance method
I don't understand the point of having two ways to call a class member if they are the same? I know this is a common question on this forum, yet I really don't understand why we would use different words to refer to the same thing (we even could use any variable name instead of self or cls).
update
In the following case:
class maclass():
A = "class method, "
def __init__(self):
self.A = "instance method, "
def getA_s(self):
print(self.A) #give me "instance method, "
#classmethod
def getA_c(cls):
print(cls.A) #give me "class method, "
C = maclass()
C.getA_s()
C.getA_c()
print(' ')
print(C.A) #give me "instance method, "
I get :
instance method,
class method,
instance method,
So in this case, in maclass: cls.A and self.A do not refer to the same variable.
All your methods are instance methods. None of them are class methods.
The first argument to a method is named self only by convention. You can name it anything you want, and naming it cls instead will not make it a reference to the class. That the first argument is bound to an instance is due to how method lookup works (accessing C.getA_s produces a bound method object, and calling that object causes C to be passed into the original function getA_s), the names of the parameters play no role.
In your methods, you are merely referencing instance attributes. That the A attribute is ultimately only defined on the class doesn't matter, you are still accessing that attribute through C.A (where C is the instance you created), not maclass.A. Looking up an attribute on the instance will also find attributes defined on the class if there is no instance attribute shadowing it.
To make a method a class method, decorate it with the #classmethod decorator:
#classmethod
def getA_c(cls):
print(cls.A)
Now cls will always be a reference to the class, never to the instance. I need to stress again that it doesn't actually matter to Python what name I picked for that first argument, but cls is the convention here as that makes it easier to remind the reader that this method is bound to the class object.
Note that if you do this for the getB_c() method, then trying to access cls.B in the method will fail because there is no B attribute on the maclass class object.
That's because classmethod wraps the function in a descriptor object that overrides the normal function binding behaviour. It is the descriptor protocol that causes methods to be bound to instances when accessed as attributes on the instance, a classmethod object redirects that binding process.
Here is a short demonstration with inline comments, I used the Python convertions for naming classes (using CamelCase), and for instances, attributes, functions and methods (using snake_case):
>>> class MyClass():
... class_attribute = "String attribute on the class"
... def __init__(self):
... self.instance_attribute = "String attribute on the instance"
... #classmethod
... def get_class_attribute(cls):
... return cls.class_attribute
... def get_instance_attribute(self):
... return self.instance_attribute
... #classmethod
... def get_instance_attribute_on_class(cls):
... return cls.instance_attribute
...
>>> instance = MyClass()
>>> instance.class_attribute # class attributes are visible on the instance
'String attribute on the class'
>>> MyClass.class_attribute # class attributes are also visible on the class
'String attribute on the class'
>>> instance.get_class_attribute() # bound to the class, but that doesn't matter here
'String attribute on the class'
>>> instance.class_attribute = "String attribute value overriding the class attribute"
>>> instance.get_class_attribute() # bound to the class, so the class attribute is found
'String attribute on the class'
>>> MyClass.get_instance_attribute_on_class() # fails, there is instance_attribute on the class
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in get_instance_attribute_on_class
AttributeError: type object 'MyClass' has no attribute 'instance_attribute'
Note that the class method accesses the class attribute even though we set an attribute with the same name on the instance.
Next is binding behaviour:
>>> MyClass.get_instance_attribute # accessing the method on the class gives you the function
<function MyClass.get_instance_attribute at 0x10f94f268>
>>> instance.get_instance_attribute # accessing the method on the instance gives you the bound method
<bound method MyClass.get_instance_attribute of <__main__.MyClass object at 0x10f92b5f8>>
>>> MyClass.get_class_attribute # class methods are always bound, to the class
<bound method MyClass.get_class_attribute of <class '__main__.MyClass'>>
>>> instance.get_class_attribute # class methods are always bound, to the class
<bound method MyClass.get_class_attribute of <class '__main__.MyClass'>>
The bound methods tell you what they are bound to, calling the method passes in that bound object as the first argument. That object can also be introspected by looking at the __self__ attribute of a bound method:
>>> instance.get_instance_attribute.__self__ # the instance
<__main__.MyClass object at 0x10f92b5f8>
>>> instance.get_class_attribute.__self__ # the class
<class '__main__.MyClass'>
From 3. Data model:
Instance methods
An instance method object combines a class, a class instance and any
callable object (normally a user-deļ¬ned function).
If it is a definition, what does it mean?
If it is not a definition, what is the definition of an "instance method"?
Is an "instance method" the same concept of a method of a class?
Since someone brings up class methods and static methods, bound methods and unbound methods, let me clarify:
I understand a method of a class can be an ordinary method, a class method, or a static method. I understand a method of a class accessed via the class or its instance can be bound or function. I have never heard of "an instance method". I don't know what it is even after looking at the quote and am not sure if it is related to a ordinary method, a class method, or a static method, or a bound method or function.
>>> class Foo:
... def im_a_method(self):
... pass
...
>>> x = Foo()
>>> x.im_a_method
<bound method Foo.im_a_method of <__main__.Foo object at 0x7f4f1993dd30>>
Tada! That's an instance method object. It's the thing you get when you retrieve a method of an object, before you call it.
What is an instance method?
An instance method is a function the is bound to a class instance. The instance of the class is implicitly passed as the first argument to instance methods. It essentially belongs to that specific instance. An instance method is the "normal" type of method people use. This is opposed to a static method or class method created using staticmethod and classmethod respectively.
Here's an example of an instance method:
>>> class Class:
... def method(self):
... pass
>>> Class.method
<bound method Class.method of <Class object at 0x7f12781c5b70>>
It's that simple.
Your confusion comes from what exactly this definition is about. The term "instance method" is actually used to describe both the concept (a method that works on an instance - by opposition with a classmethod or staticmethod) and its technical implementation. The definition you quote is about the technical implementation.
If you want to understand the context of this definition, you can read this article in the Python wiki, which explains how Python turns functions into methods at runtime.
An instance method:
can call instance and class variables and instance, class and static methods by self.
can call class variables and instance, class and static methods by class name but not instance variables.
can be called by object.
can be also called directly by class name but when called directly by class name, we need to pass one argument to the instance method because self becomes the normal parameter which doesn't have the ability to call instance and class variables and instance, class and static methods.
needs self for the 1st argument otherwise the instance method cannot be called by an object but the instance method can still be called directly by class name and the name of self is used in convention so other names instead of self still work.
*I also explain about #classmethod and #staticmethod in my answer for #classmethod vs #staticmethod in Python.
For example, the instance method can call the instance and class variables and the instance, class and static methods by self and the instance method can call the class variable and the instance, class and static methods by class name but not the instance variables and the instance method can be called by object as shown below:
class Person:
x = "Hello"
def __init__(self, name):
self.name = name
def test1(self): # Instance method
print(self.name) # Instance variable by "self"
print(self.x) # Class variable by "self"
self.test2() # Instance method by "self"
self.test3() # Class method by "self"
self.test4() # Static method by "self"
print()
print(Person.x) # Class variable by class name
Person.test2("Test2") # Instance method by class name
Person.test3() # Class method by class name
Person.test4() # Static method by class name
def test2(self):
print("Test2")
#classmethod
def test3(cls):
print("Test3")
#staticmethod
def test4():
print("Test4")
obj = Person("John")
obj.test1() # By object
Output:
John # Instance variable by "self"
Hello # Class variable by "self"
Test2 # Instance method by "self"
Test3 # Class method by "self"
Test4 # Static method by "self"
Hello # Class variable by class name
Test2 # Instance method by class name
Test3 # Class method by class name
Test4 # Static method by class name
And, if the instance method tries to call the instance variable by class name as shown below:
# ...
def test1(self): # Instance method
print(Person.name) # Instance variable by class name
obj = Person("John")
obj.test1()
The error below occurs:
AttributeError: type object 'Person' has no attribute 'name'
And, the instance method can be also called directly by class name but when called directly by class name, we need to pass one argument to the instance method as shown below because self becomes the normal parameter which doesn't have the ability to call the instance and class variables and the instance, class and static methods by self:
# ...
def test1(self): # Instance method
print(self)
# ...
Person.test1("Test1") # Here
Output:
Test1
So, if the instance method tries to call the instance and class variables and the instance, class and static methods by self as shown below:
# ...
def test1(self): # Instance method
print(self.name) # Instance variable or
print(self.x) # Class variable or
self.test2() # Instance method or
self.test3() # Class method or
self.test4() # Static method
# ...
Person.test1("Test1") # Here
The errors below occur because again, self becomes the normal parameter which doesn't have the ability to call the instance and class variables and the instance, class and static methods:
AttributeError: 'str' object has no attribute 'name'
AttributeError: 'str' object has no attribute 'x'
AttributeError: 'str' object has no attribute 'test2'
AttributeError: 'str' object has no attribute 'test3'
AttributeError: 'str' object has no attribute 'test4'
And, if one argument is not passed to the instance method as shown below:
# ...
def test1(self): # Instance method
print(self)
# ...
Person.test1() # Here
The error below occurs:
TypeError: test1() missing 1 required positional argument: 'self'
And, the instance method needs self for the 1st argument otherwise the instance method cannot be called by object as shown below:
# ...
def test1(): # Without "self"
print("Test1")
# ...
obj = Person("John")
obj.test1() # Here
Then, the error below occurs:
TypeError: test1() takes 0 positional arguments but 1 was given
But, the instance method without self can still be called directly by class name as shown below:
# ...
def test1(): # Without "self"
print("Test1")
# ...
Person.test1() # Here
Output:
Test1
And, the name of self is used in convention in an instance method so other name instead of self still works as shown below:
# ...
# Here
def test1(orange): # Instance method
print(orange.name) # Instance variable
print(orange.x) # Class variable
orange.test2() # Instance method
orange.test3() # Class method
orange.test4() # Static method
# ...
obj = Person("John")
obj.test1()
Output:
John
Hello
Test2
Test3
Test4
In python, is there a way to get the class name in the "static constructor"? I would like to initialize a class variable using an inherited class method.
class A():
#classmethod
def _getInit(cls):
return 'Hello ' + cls.__name__
class B(A):
staticField = B._getInit()
NameError: name 'B' is not defined
The name B is not assigned to until the full class suite has been executed and a class object has been created. For the same reason, the __name__ attribute on the class is not set until the class object is created either.
You'd have to assign that attribute afterwards:
class A():
#classmethod
def _getInit(cls):
return 'Hello ' + cls.__name__
class B(A):
pass
B.staticField = B._getInit()
The alternative is to use a class decorator (which is passed the newly-created class object) or use a metaclass (which creates the class object in the first place and is given the name to use).
I would like to know how to convert parent object that was return by some function to child class.
class A(object):
def __init__():
pass
class B(A):
def functionIneed():
pass
i = module.getObject() # i will get object that is class A
j = B(i) # this will return exception
j.functionIneed()
I cannot change class A. If I could I would implement functionIneed to class A, but it is impossible because of structure of code.
Python does not support "casting". You will need to write B.__init__() so that it can take an A and initialize itself appropriately.
I have a strong suspicion, nay, conviction, that there is something horribly wrong with your program design that it requires you to do this. In Python, unlike Java, very few problems require classes to solve. If there's a function you need, simply define it:
def function_i_need(a):
"""parameter a: an instance of A"""
pass # do something with 'a'
However, if I cannot dissuade you from making your function a method of the class, you can change an instance's class by setting its __class__ attribute:
>>> class A(object):
... def __init__(self):
... pass
...
>>> class B(A):
... def functionIneed(self):
... print 'functionIneed'
...
>>> a = A()
>>> a.functionIneed()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'functionIneed'
>>> a.__class__ = B
>>> a.functionIneed()
functionIneed
This will work as long as B has no __init__ method, since, obviously, that __init__ will never be called.
You said you want to implement something like this:
class B(A):
def functionIneed():
pass
But really what you would be making is something more like this (unless you had intended on making a class or static method in the first place):
class B(A):
def functionIneed(self):
pass
Then you can call B.functionIneed(instance_of_A). (This is one of the advantages of having to pass self explicitly to methods.)
You did not correctly define your classes.
Should be like this:
class A(object):
def __init__(self):
pass
class B(A):
def __init__(self):
super(B,self).__init__()
def functionIneed(self):
pass
Then you can
j=B()
j.fuctionIneed()
as expected
You forgot to refer to the ins
Just thinking outside the box:
Instead of a new class with the function you want, how about just adding the function to the class or instance you already have?
There is a good description of this in
Adding a Method to an Existing Object Instance
How about:
i = module.getObject() # i will get object that is class A
try:
i.functionIneed()
except AttributeError:
# handle case when u have a bad object
Read up on duck typing.