內置屬性
創建類時系統自動創建的屬性
# 內置屬性:dir(對象),列出所有的內置屬性
class Person(object):'''Person類1'''# Person類2__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = agedef eat(self):print("eat!!!")p = Person('name',17)
print(dir(p))
# 輸出
# ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'eat']
print(p.__class__)
#將對象所支持的所有屬性和函數列出。
print(p.__dir__)
#顯示的是多行注釋
print(p.__doc__)
print(Person.__doc__)
#主方法
print(p.__module__)
對象屬性
類屬性
# 類屬性
class Person(object):type = 'mm'__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = agedef eat(self):print("eat!!!")p=Person('name',19)
#通過對象和類名調用類屬性
print(p.type)
print(Person.type)
#只能通過類名修改類屬性
Person.type='upq'
print(Person.type)
print(p.type)
#輸出
# mm
# mm
# upq
# upq
私有屬性
# 私有屬性
class Teacher():def __init__(self):self.__name='ert'self.__level=99#獲取老師的等級def get_level(self):return self.__level#獲取名字def get_in_name(self):return self.__namedef set_in_name(self,name):self.__name=name
t=Teacher()
# #獲取私有屬性1
print("name is",t._Teacher__name) #輸出GG
t._Teacher__name="AA" #被改變了
print("name is",t._Teacher__name) #輸出AA
#獲取私有屬性2
t.set_in_name('pppp')
print(t.get_in_name())#輸出
# name is GG
# name is AA
# pppp
私有方法
#function:私有方法
class Person(object):def __init__(self):self.__p=100def __xx(self):print(self.__p)
p1=Person()
print(p1._Person__p)
p1._Person__xx()
實例方法
類方法
靜態方法
總結:實例方法 & 類方法 & 靜態方法
靜態方法:當用不到當前類和對象屬性時(感覺與當前類沒關系一樣),可以定義為靜態方法(一個定義在類中的普通方法)
# author:dq
# project:PythonProject
# date:2021年10月21日
# function:實例方法 & 類方法 & 靜態方法class Person():type = 'type'__slots__ = ('name', 'age')def __init__(self, name, age):self.name = nameself.age = age# 實例方法def common(self):print('common')# 類方法@classmethoddef classmethod(cls):cls.type = 'class type'print(cls.type)print('classmethod')# 靜態方法@staticmethoddef staticmethod():print('static')
p=Person('name',77)
#對象調用
p.common()
p.classmethod()
p.staticmethod()
#類調用
Person.common(p)
Person.classmethod()
Person.staticmethod()