python3中类和对象

转载自 https://www.cnblogs.com/cdinc/p/5860351.html

静态变量
我们可以在类中定义静态变量,静态变量属于类,既可以使用类访问,也可以使用对象访问。

class Car(object):
    type='car'
c1=Car()
print(c1.type)
print(Car.type)

动态变量
动态变量属于类,在第一次创建类的时候传入类中。动态变量只属于对象,只能由对象访问。

class Car(object):
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
c1=Car('Lamborghini','yellow')
print('name:%s,colour:%s'%(c1.name,c1.colour))

动态方法
类的动态方法是自定义的方法,同时只有对象能够调用。

class Car(object):
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
    def show(self):
        print("The car's name is %s and colour is %s." % (self.name, self.colour))    
c1=Car('Lamborghini','yellow')
print('name:%s,colour:%s'%(c1.name,c1.colour))
c1.show()

静态方法
有动态方法必然会有静态方法。静态方法属于类,类和对象都可以进行调用。需要在定义静态方法前加入装饰器@staticmethod,并且不传入self参数。

class Car(object):
    @staticmethod
    def description():
        print('This is a very fast car.')
c1=Car()
c1.description()
Car.description()

类的属性
在方法前面加入@property装饰器,这个方法就变成了类的属性,可以以调用属性的方式进行方法的调用。注意在运行时不需要添加括号

class Car(object):
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
    @property
    def show(self):
        print("The car's name is %s and colour is %s." % (self.name, self.colour))
c1=Car('Lamborghini','yellow')
c1.show

私有变量
在变量前面加入两个下划线就将这个变量变为了私有变量,创建的对象没有变法访问私有变量,私有变量只能内部访问。

class Car(object):
    def __init__(self, name, colour):
        self.__name = name
        self.__colour = colour
    def show(self):
        print("The car's name is %s and colour is %s." % (self.__name, self.__colour))
c1=Car('Lamborghini','yellow')
c1.show()

当然,私有变量也可以利用类的特性来访问

class Car(object):
    def __init__(self, name, colour):
        self.__name = name
        self.__colour = colour
    def show(self):
        print("The car's name is %s and colour is %s." % (self.__name, self.__colour))
    @property
    def name(self):
        return self.__name
c1=Car('Lamborghini','yellow')
c1.show()
print(c1.name)

私有方法
将方法前面加上两个下划线就会变成私有方法,外部就无法访问这个方法了。而如果要访问这个方法只能在类的内部才可以访问。

class Car(object):
    def __init__(self, name, colour):
        self.__name = name
        self.__colour = colour
    def __show(self):
        print("The car's name is %s and colour is %s." % (self.__name, self.__colour))
    def func(self):
        self.__show()
c1=Car('Lamborghini','yellow')
c1.func()

析构函数
_init_()在对象被创建的时候进行调用,成为构造函数。而对象被销毁的时候就会调用_del_()函数,成为析构函数。

class Car(object):
    def __init__(self):
        print('我被创建了')
    def __del__(self):
        print('我要被销毁了')
c1=Car()

_call_方法
python中也有一个方法叫做_call_(),这个方法是干什么用的呢?当对象作为一个函数进行执行的时候,就会执行这个方法。

class Car(object):
    def __call__(self, *args, **kwargs):
        print('call')
c1=Car()
c1()

猜你喜欢

转载自blog.csdn.net/thomas_zefan/article/details/82183768