python 学习第十四天(类和对象)

类和对象

  • 类的定义和实例化对象

class dog:

    eye_num=2
    #类属性,不依赖于实例化对象
    def __init__( self,color, type, name):
        # init 函数是初始化一个实例的,self关键字表示实例自己
        self.color = color
        self.type = type
        self.name = name

    # 上面三个都是实例属性,它依赖于实例对象


    def cry(self):  # 类的方法,本质就是函数,叫法不同而已
        print('%s正在叫'%(self.name))
a = dog('yellow','哈士奇','哈哈')  # 实例化一个dog对象,self是不用我们传,python解释器会自动传
a.cry()  # 调用方法
  • 静态属性
    本质:把一个方法做成属性
class house:
    def __init__( self,length ,wide):
        self.length= length
        self.wide = wide
    @property. #在一个方法上面加上`@property`就变成了静态属性
    def area(self):
        return self.length*self.wide
a=house(20,20)
print(a.area)
  • 类方法
    一个方法不需要实例就可以调用的方法,但实例还是可以调用这个方法。而且类方法只能使用类属性
class house:
    wide=13
    def __init__( self,length ,wide):
        self.length= length
        self.wide = wide
    @property
    def area(self):
        return self.length*self.wide


    @classmethod
    def a(cls):
        print(cls.wide)


    def b(self):
        print('b')
house.a(). #13
house.b()  #TypeError: b() missing 1 required positional argument: 'self'
#就是说b方法必须要有实例才可以

b=house(12,22)
house.b(b) #b
b.a() #13
  • 静态方法
    静态方法只是名义上归属类管理,不能使用类属性和实例属性。和类方法一样也可以 通过类名来调用
class house:
    wide=13
    def __init__( self,length ,wide):
        self.length= length
        self.wide = wide
    @property
    def area(self):
        return self.length*self.wide


    @classmethod
    def a(cls):
        print(cls.wide)    



    @staticmethod 
    def b():
        print('b')
house.b()

猜你喜欢

转载自blog.csdn.net/CZ505632696/article/details/81294830