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