美文网首页
python基础知识(三)--面向对象编程

python基础知识(三)--面向对象编程

作者: Godric_wsw | 来源:发表于2018-09-01 16:11 被阅读6次

    1.Demo

    class test(object):
        static_text = 'static test'
    
        def __new__(cls, *args, **kwargs):
            print("__new__")
            #return wang()
            return object.__new__(cls, *args, **kwargs)
    
        def __init__(self):
            print("__init__")
            self.normal_text = 'normal_text'
    
        def __call__(self):
            print('call 911')
    
        def __str__(self):
            return "class description"
    
        def normal_function(self):
            print('normal function')
    
        @classmethod
        def cls_function(cls):
            print('cls function')
    
        @classmethod
        def cls_function01(cls):
            print('cls function')
        @staticmethod
        def static_method():
            print('static method')
    
        @property
        def prop(self):
            new_price = self.normal_text
            return new_price
    
        @prop.setter
        def prop(self,value):
            self.normal_text = value
    
        @prop.deleter
        def prop(self):
            del self.normal_text
    
    
        def _get_post(self):
            return self.normal_text
        def _set_post(self,value):
            self.normal_text = value
        def _del_post(self):
            print("WANG")
        POST = property(_get_post,_set_post,_del_post)
    
    mytest = test()
    #ordinary function
    print(mytest.normal_text)
    mytest.normal_function()
    mytest()
    print(mytest)
    
    #property
    print(mytest.POST)
    mytest.POST = 'WANG01'
    del mytest.POST
    
    #static method
    print(mytest.static_text)
    print(test.static_text)
    mytest.static_method()
    mytest.cls_function()
    

    2.类的初始化过程

    • 先调用_new_方法,再调用_init_方法。
    • _new_方法常 用于一些设计模式中,如单例模式,平时较少使用
    • _init_方法,用于类初始化时一些初始参数的设置,一般写个类的时候,都会有一个_init_方法
    mytest = test() # 先__new__,再 __init__
    

    3.类成员

    • 字段
      静态字段:static_text
    # 静态字段调用
    print(mytest.static_text)
    print(test.static_text)
    

    普通字段:self.normal_text

    print(mytest.normal_text) # 普通字段调用
    
    • 方法
      普通方法: normal_function
    mytest.normal_function()
    

    类方法: cls_function

    mytest.cls_function()
    test.cls_function()
    

    静态方法: static_method

    mytest.static_method()
    test.static_method()
    
    • 属性: 有两种设置方法(@property, 或者property)
      普通属性
    print(mytest.POST)
    mytest.POST = 'WANG01'
    print(mytest.POST)
    del mytest.POST
    
    • _call_方法
    mytest()  # __call__调用方法
    
    • _str_方法
    print(mytest) #  __str__调用方法
    
    • 所有成员中,只有普通字段的内容保存在对象中。其他成员,则保存在类中。
    • 即此类创建了多少对象,在内存中就有多少个普通字段。面其他成员,无论对象多少,在内存中,只创建一份。

    相关文章

      网友评论

          本文标题:python基础知识(三)--面向对象编程

          本文链接:https://www.haomeiwen.com/subject/rhluwftx.html