python,面向对象的各种方法
生活随笔
收集整理的這篇文章主要介紹了
python,面向对象的各种方法
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1,靜態(tài)方法 ?(用這個裝飾器來表示 ?@staticmethod ?)
意思是把?@staticmethod 下面的函數(shù)和所屬的類截斷了,這個函數(shù)就不屬于這個類了,沒有類的屬性了,只不是還是要通過類名的方式調(diào)用 ?
看個小例子:
錯誤示例:class Person(object):def __init__(self, name):self.name = name@staticmethod # 把eat方法變?yōu)殪o態(tài)方法def eat(self):print("%s is eating" % self.name)d = Person("xiaoming") d.eat() ############## 結(jié)果: TypeError: eat() missing 1 required positional argument: 'self'因為用靜態(tài)方法把eat這個方法與Person這個類截斷了,eat方法就沒有了類的屬性了,所以獲取不到self.name這個變量。 ?
正確示例: class Person(object):def __init__(self, name):self.name = name@staticmethod # 把eat方法變?yōu)殪o態(tài)方法def eat(x):print("%s is eating" % x)d = Person("xiaoming") d.eat("jack") #就把eat方法當作一個獨立的函數(shù)給他傳參就行了?
?
2,類方法 ?(用這個裝飾器來表示 @classmethod)
類方法只能訪問類變量,不能訪問實例變量
看個例子:
錯誤示例: class Person(object):def __init__(self, name):self.name = name@classmethod # 把eat方法變?yōu)轭惙椒?/span>def eat(self):print("%s is eating" % self.name)d = Person("xiaoming") d.eat() ########### 結(jié)果: AttributeError: type object 'Person' has no attribute 'name'因為self.name這個變量是實例化這個類傳進去的,類方法是不能訪問實例變量的,只能訪問類里面定義的變量 ??
class Person(object):name="杰克"def __init__(self, name):self.name = name@classmethod # 把eat方法變?yōu)轭惙椒?/span>def eat(self):print("%s is eating" % self.name)d = Person("xiaoming") d.eat()?
?
3,屬性方法 (用這個裝飾器表示 @property)
把一個方法變成一個靜態(tài)屬性,屬性就不用加小括號那樣的去調(diào)用了
看個小例子:
錯誤示例: class Person(object):def __init__(self, name):self.name = name@property # 把eat方法變?yōu)閷傩苑椒?/span>def eat(self):print("%s is eating" % self.name)d = Person("xiaoming") d.eat() ########## 結(jié)果: TypeError: 'NoneType' object is not callable因為eat此時已經(jīng)變成一個屬性了, 不是方法了, 想調(diào)用已經(jīng)不需要加()號了,直接d.eat就可以了?
class Person(object):def __init__(self, name):self.name = name@property # 把eat方法變?yōu)閷傩苑椒?/span>def eat(self):print("%s is eating" % self.name)d = Person("xiaoming") d.eat?
轉(zhuǎn)載于:https://www.cnblogs.com/nianqingguo/p/5855768.html
總結(jié)
以上是生活随笔為你收集整理的python,面向对象的各种方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编写高质量代码:改善Java程序的151
- 下一篇: 第 3 章 共享程序集和强命名程序集