添加和获取对象属性

说明

属性即是特征,⽐如:人的年龄、性别、体重...

对象属性既可以在类外⾯添加和获取,也能在类⾥⾯添加和获取。

类外添加或修改对象属性

语法

对象名.属性名 = 值

类外访问对象属性

语法

对象名.属性名

类内访问、修改、添加对象属性

使用self代替对象名访问、修改、添加对象属性

 

 

示例


'''
给对象添加、修改属性
'''


class Person:
def __init__(self, name, age):
# self.sex = None # 建议在此处添加
self.name = name
self.age = age

def say_hello(self):
# 类里面访问对象属性:self.属性名
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
self.sex = 1 # 不建议在普通方法里添加属性
print(self.sex) # 1


# 1. 创建Person对象
person = Person("Allen", 25)

# 2. 在类外添加属性身高
person.height = 178
print(person.height) # 178
# 3. 在类外修改身高
person.height = 175
# 4. 类外获取对象属性值
print(person.height) # 175

person.say_hello()
 
posted @ 2023-07-12 22:01  Allen_Hao  阅读(31)  评论(0)    收藏  举报