code show as below:
class Cat:
#属性
new_name = 0
new_age = 0
#方法
def get_name(self,new_name):
return new_name
def get_age(self,new_age):
return new_age
def Attributes(self):
self.name = self.get_name(self.new_name)
self.age = self.get_age(self.new_age)
print(self.name)
print(self.age)
def show(self):
print(self.name)
print(self.age)
#cat = Cat()
cat = Cat()
cat.get_name("哈哈")
cat.get_age(20)
cat.Attributes()
cat.show()
Results of the:
my question:
I have passed in 2 values, one haha and one 20
Why is it still printed as 0?
To put it simply, your get function did not assign your variables "haha" and 20 to the attributes of the class
The arrow you drew actually points to the two get functions above, not your Attr function.
Your
cat.get_name("haha")
returns the value of a local variablenew_name
and does not change the value ofself.new_name
, so executeself.name = self.get_name(self.new_name)
Afterself.name
is still0
.Your attributes new_name and new_age belong to Cat attributes. To assign and access class attributes, you must use class objects. Access in this class is self (representing the object of this class can be understood as the this pointer in C++, through self You can call the attributes and methods of the class), and you did not assign values to the attributes of the class in get_name and get_age, but just returned the data passed in by the method, so the attributes new_name and new_age of the Cat class have not been reassigned and remain the same. 0. If you want to change the new_name and new_age values of the Cat class, you can change them to:
def get_name(self, new_name):
def get_age(self, new_age):
Or provide set method:
def set_new_name(self, new_name):
def set_new_age(self, new_age):
def get_name(self):
def get_age(self):
This just returns the parameters of the function directly and does nothing else. You can try to execute
print(cat.get_name('xxx'))
to see the return result of this function. The class attributenew_name
is still0
. Therefore, inAttributes
, it is equivalent to passing in 0, soself.name
also gets0
. This is why the printed result is still0
.But it seems that you are still in the entry-level stage, and you may have transferred from Java. . . So if you want to fundamentally solve this type of problem, I have the following suggestions.
Don’t use
get
andset
naked. It is recommended to use@property
and search this keyword to learn related knowledge.You try to use
self
to accessname
in theCat
class, indicating that you want this to be an instance attribute. Please put all instance attributes in__init__
, and do not initialize instance attributes in other methods.It is recommended to further consolidate the Python foundation.