python中的类属性以及类方法

1. 类属性
类属性:
    所有对象共用,共享的属性,不属于某一个对象,所有的对象都能使用这个属性,
    只要有一个对象修改里这个属性值,就会影响其他对象使用这个属性.
定义:

    定义在方法的外面,类的里面

调用类属性格式:
    1.类名.类属性名
    2.对象名.类属性名

注意:在类的外面修改类属性的值,需要通过类名来修改,而不能直接修改

class Student:
# 定义类属性
kong_tiao = "格力中央空调"
def study(self):
print("好好学习,天天向上!!")
# print(self.kong_tiao)
print(Student.kong_tiao)
# 1.类名.类属性名
print(Student.kong_tiao)
# 2.对象名.类属性名
s1 = Student()
print(s1.kong_tiao)

s2 = Student()
print(s2.kong_tiao)

# 给s1对象添加 实例属性 kong_tiao
s1.kong_tiao = "美的空调"
print(s1.kong_tiao)

# 在类的外面修改类属性的值,需要通过类名来修改
Student.kong_tiao = "美的空调2,类属性"
print(s2.kong_tiao)

2.类方法
    定义类方法,需要在方法的上面添加 @classmethod,用来标记该方法为一个类方法的,
    cls 表示为 类对象,就表示当前类的,cls就相当于类名
    通过cls可以访问类属性和类方法

class Student:
# 定义类属性
kong_tiao = "格力中央空调"
def study(self):
print("好好学习,天天向上!!")
@classmethod
def method02(cls):
print("method02方法...")
@classmethod
def jiao_zuo_ye(cls):
print("交作业的方法...")
print(cls.kong_tiao) # print(Student.kong_tiao)
cls.method02()
# ######在这个方法中不能访问实例属性和实例方法
# self.study()
s = Student()
s.jiao_zuo_ye()
s.method02()

 

类方法不能调用示例方法和属性,但是实例方法可以调用类属性和类方法

猜你喜欢

转载自blog.csdn.net/cestlavieqiang/article/details/81092957
今日推荐