Python面向对象学习笔记-类、属性、方法

定义类

函数 python2 python3
定义普通类 class name(object): class name:
构造函数 def__init__(self, parameter1,parameter2 …):
析构函数 def__del__(sel, parameter1, parameter2 …):
查看类型 type()
查看属性 dir()

定义类的属性

  • 在_ _ init _ _()外初始化
  • 在内部用className.类属性名调用或直接类属性名
  • 外部既可以用className.类属性名又可以用instancename.类属性名来调用

定义实例属性

  • 最好在_ _ init _ _(self,…)中初始化
  • 内部调用时都需要加上self.
  • 外部调用时用instanceName.propertyName

属性访问权限

  • 无下划线+属性名,相当于公有属性,类内类外皆可访问
  • 单下划线+属性名,只是告诉别人这是私有属性,外部依然可以访问更改
  • 双下划线+属性名, 外部不可通过instanceName.propertyName来访问或者更改
    外部可以用instancName. _className__propertyName来访问

定义类的方法

  1. 普通类方法:
    def fun_name(self,…):
    pass
    外部用实例调用
  2. 静态方法:@staticmethod
    不能访问实例属性!!! 参数不能传入self!!!
    与类相关但是不依赖类与实例的方法!!
  3. 类方法:@classmethod
    不能访问实例属性!!! 参数必须传入cls!!!
    self代表实例对象,调用类属性:cls.类属性名
    静态方法与类方法都可以通过类或者实例来调用,但都不能够调用实例属性
  4. 创建只读属性,像使用属性一样调用方法:@property

example 1

类,方法,属性的使用

class Programmer:
    age = 12
    _music = 'none'
    __more = 'more'
    def __init__(self, name, hobby):
        self.__name = name
        self.__hobby = hobby

    @property  #创建只读属性,像使用属性一样调用方法
    def name(self):
        print("I am not a property but a function")
        return self.__name

    @classmethod   #可以不用实例化,用类名调用方法
    def getMore(cls):
        return cls.__more

if __name__=="__main__":
    a = Programmer("learningpython", "coding")  #创建一个Programmer实例对象
    print(Programmer.getMore())    #使用@classmethod定义的类方法,获取私有类属性的值
    print(a.name)                  #使用@property 修饰的方法,像使用属性一样调用name()方法并获取其返回值
    print(Programmer.age)          #使用类名.类属性名的方式获取公有的类属性
    print(Programmer._music)       #使用类名.类属性名的方式获取 可以访问 但暗示你是私有的 不要随意访问的 类属性
    print(a._Programmer__hobby)     #类外访问私有实例属性名
    print(a._Programmer__more)      #类外访问私有类属性名

out result :
more
I am not a property but a function
learningpython
12
none
coding
more
Process finished with exit code 0

example 2

property 的 getter,setter 和 deleter 方法用作装饰器

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x
if __name__ == "__main__":
    aIsinstance = C()
    print(aIsinstance.x)
    aIsinstance.x = 5         #相当于调用@x.setter后的函数def x (self,  5):
    print(aIsinstance.x)
    del aIsinstance.x         #相当于调用@x.deleter后的函数def x (self): ,删除了新建的实例
    #print(aIsinstance.x)     #删除后便无法print了,不然会出错

out result:
None
5
Process finished with exit code 0

进一步更细致地了解@property,可以看一下这篇博客

猜你喜欢

转载自blog.csdn.net/qq_38195197/article/details/79865355