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

 

posted @ 2016-09-09 10:57  疯狂的大叔  阅读(1358)  评论(0编辑  收藏  举报