类属性和类方法
类属性
类属性与实例属性的特点
类属性:类对象所拥有的属性,
1,类属性访问
class BMW():
brand = 'BMW'
def __init__(self,color,style):
self.style = style
self.color = color
#第一种访问方法
BMW.brand
#第二种访问方式
obj1 = BWM('x1','白色')
print(obj1.brand)
2、私有类属性
class BMW():
brand = 'BMW'
__money = 1000
def __init__(self,color,style):
self.style = style
self.color = color
1、私有类属性只能在类的内部使用,外部无法访问,调用方法和上面都一样
3、修改类属性
class BMW():
brand = 'BMW'
__money = 1000
def __init__(self,color,style):
self.style = style
self.color = color
1 通过类对象进行修改
BMW.brand = 'aaaa'
#可以成功修改
2 通过实例对象来修改
a = BMW('X1','白色')
a.brand = 'bbbb'
#同样也可以修改但是只是增加了一个动态实例属性 类似创建了临时属性覆盖了原来的值
类方法
格式
要添加@classmethod
# class BMW():
# __money = 1000
# brand = 'BMW BMW BMW'
# @classmethod
# def change(cls,brand):
# cls.brand = brand
# a.change('AAAA') #实例调用类方法
# BMW.change('aaa') #类对象调用类方法
类方法可以通过类对象访问,也可以通过实例对象访问
1428

被折叠的 条评论
为什么被折叠?



