类成员: 字段(保存在对象中) 方法(保存在类中)
class Foo:
def __init__(self, name):
# 字段
self.name = name
# 方法
def show(self):
print(self.name)
obj = Foo('alex')
obj。name
obj.show()
# alex
# 类成员:字段(保存在对象中) 方法(保存在类中)
另外,字段又可以分为普通字段和静态字段,其中普通字段属于对象,只能通过对象访问,静态字段属于类,可以通过对象访问,也可以通过类访问。
# 中国的所有省份,用面向对象知识表示?
class Province:
# country叫静态字段,属于类
country = '中国'
def __init__(self, name):
# self.name叫普通字段,属于对象
self.name = name
print(Province.country) # 中国
henan = Province('河南')
print(henan.name) # 河南
print(henan.country) # 中国