本文內(nèi)容:
- 類的創(chuàng)建
- 類變量瘪匿、類方法的創(chuàng)建和調(diào)用
- 實(shí)例變量跛梗、實(shí)例方法的創(chuàng)建和調(diào)用
- 靜態(tài)方法的創(chuàng)建和調(diào)用
- 私有變量、方法的創(chuàng)建和調(diào)用
定義一個(gè)類Student棋弥,包含類變量核偿、實(shí)例變量、實(shí)例方法
class Student():
# 類變量
name = "張三"
def __init__(self):
# 實(shí)例變量
self.name = "張三"
# 實(shí)例方法
def run(self):
return self.name
print(Student.name)
print(Student().name)
print(Student().run())
>>>
張三
張四
張四
類變量:可以通過類直接訪問:Student.name
實(shí)例變量:需要實(shí)例化后才能訪問:Student().name
實(shí)例方法:需要實(shí)例化后才能訪問:Student().run()
顽染,實(shí)例方法可以訪問實(shí)例變量
類方法定義
在類前面加上 @classmethod
# 類方法
@classmethod
def run2(cls):
return cls.name
靜態(tài)方法定義
在類前面加上 @staticmethod
@staticmethod
def run3():
print("staticmethod run")
* 實(shí)例變量和實(shí)例方法只能實(shí)例化后才能訪問漾岳,類方法、類變量粉寞、靜態(tài)方法不受限制尼荆。
私有變量、方法的定義和訪問
定義:在變量名前加上__
如: __name
訪問:_類名__name
舉個(gè)例子:
class Student():
# 私有變量
__name = "張三"
# 私有方法
def __run(self):
print("run")
print(Student._Student__name)
Student()._Student__run()
>>>
張三
run