AttributeError: 'person' object has no attribute 'name' - python

class Name():
def full_name(self):
self.firstname='[no name]'
self.lastname='[no name]'
class person:
def detail(self):
self.name=Name()
self.eye='[no eye]'
self.age=-1
myperson=person()
myperson.name.firstname='apple'
myperson.name.lastname='regmi'
myperson.name.firstname='cat'
print(myperson.name.firstname)
i could not find out why iam getting line 13, in
myperson.name.firstname='apple' AttributeError: 'person' object has no attribute 'name'

It seems like you're hoping to set the name, eye, and age attributes as defaults when you create any person object. If that's the case, detail should really be replaced with __init__, e.g.:
class person:
def __init__(self):
self.name=Name()
self.eye='[no eye]'
self.age=-1
A class's __init__ method defines how objects should be initialized when they are created. You don't need to call this method explicitly; instead, it is automatically run when you create an instance of a class:
# create an instance of persion, call
# `person.__init__()`, and assign the result
# to `myperson`:
myperson = person()
Now you should be able to reference and assign the attributes:
myperson.name.firstname='apple'
myperson.name.lastname='regmi'
myperson.name.firstname='cat'
Similarly, name.full_name should probably be name.__init__.
Note that by convention, classes in python usually use TitleCase, so this class would typically be named Person; likewise, name would be Name.

Related

Why while running the program I am getting object not callable

class College():
def __init__(self,name):
self.name = name
def name(self):
print(self.name)
a = College("IIT")
a.name()
You gave a an instance attribute named name when you called College.__init__. That shadows the class attribute (i.e., the method) with the same name. Choose a different method or attribute name.
a.name is the string "IIT", which is not callable. You can cheat a bit to get access to the method
>>> College.name(a)
IIT
but it will be cleaner to use separate names for the two attributes.
You are getting this because when you are calling the name() method but the program (python compiler) thinks that you are calling the name attribute of that object.
To prevent that from happening this just use a different name for every methods, attributes and variables.
class College():
def __init__(self,name):
self.name = name
def show_name(self):
print(self.name)
a = College("IIT")
a.show_name()

Python global class attributes

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'

Understanding the difference between `self`and `cls` and whether they refer to the same attributes

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'>

What is an "instance method"?

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

Can you use the __init__ method as a setter on an object that's already been instantiated

After creating an instance object from a class, can you use the object's init method to set it's variable to something new?
Ex:
class Object1(Object):
def __init__(self, name, ability):
self.name = name
self.ability = ability
example1 = Object1("example", "none")
#new object created with parameters set by the __init__ method
example1.__init__("changeExample", "Changed")
#called the __init__ method on the object and changed the parameters. Is this okay to do?

Categories