python (object-oriented programming)

python (object-oriented programming)

Combine your own lecturer and write your own notes. There are deficiencies, and I hope you can comment on the deficiencies. Everyone learns from each other. Welcome to leave a message.

The emergence of object-oriented
A group with the same attributes completes a big task.
After instantiating and defining the class, use this class to construct an object (the object can be many
init(self) [constructor]
self refers to the current instantiated object
python is not a real constructor, just a callback of the instance, it cannot be returned)
# Define a class
class A(object): #define class, the first letter of the name is capitalized, the default () is the parent class #object
construction (attributes include data and methods)
pass

> class P():
>     def __init__(self):
>         print('+'*20)
> 
>     def __init__(self,name,age):
>         self.name=name
>         self.age=age
>         
>     def run(self):
>         pass 
> 
> if __name__=='__main__':
>     p=P()#实例化
>     #p2=P('xxx',20)

Methods and functions are methods in different classes, and functions outside of instances.
Python dynamic language features
#define a class
class P(object ): #define a class, the first letter of the name is capitalized, the default () is the parent class #object
construction (attributes include data and methods)
pass
if name ==' main ':
p=P()
p.name='name'
p.age=10

print(p.name )
print(p.age )
print(hasattr(p,'name') )#hasatter作用在p上查找name属性
print(hasattr(p,'age') )

p.func=lambda x: x+1
print(p.func (1)) 

Object instantiation call, call instantiation #define
a class
class A(object): #define a class, the name is capitalized, and the default () is the parent class
#Object construction (attributes include data and methods)
pass

class P():


    def __init__(self,name,age):
        self.name=name
        self.age=age

    def run(self):
      print(self .name +'run...')

if __name__=='__main__':

    p2=P('xxx',20)#实例化
    print(p2 .age)
    print(p2 .name)

The difference between a variable type and an immutable type
#define a class
class A(object):#define a class, the name is capitalized, and the default () is the parent class
#object construction (attributes include data and methods)
pass

class P():
    has_two_eyes=[]#定义静态的属性
    #def func(self):
     #   print('func invoke...')

    def __init__(self,name,age):
        self.name=name
        self.age=age

    def run(self):
      print(self .name +'run...')

if __name__=='__main__':
   p1=P('p1',1)#实例化对象
   p2=P('p2',2)
  # print(P .has_two_eyes )
   #print(p1.has_two_eyes )
   #print(p2.has_two_eyes )
   ###########################
#P.has_two_eyes +=1#静态属性的更新
#print(P .has_two_eyes )
#########################
#p1 .has_two_eyes +=1
#print(P.has_two_eyes )
#print(p2.has_two_eyes )
#print(p1 .has_two_eyes )
#print(id(P.has_two_eyes ) )
#print(id(p1.has_two_eyes ) )
##########################列表表示.int是不可变,列表是可以改变的类型
p1 .has_two_eyes .append(123)
print(p1 .has_two_eyes )
print(id(P.has_two_eyes ) )
print(id(p1.has_two_eyes ) )

How to define an object (different instances, use different constructors,)
#define a class
class Name(object): #define class, name the first letter capitalized, the default () is the parent class #object
construction (attributes include data and Method (out of the constructor called function))
def init (self,name,age): #Constructor (special method) adds attributes: name, age (self is the current object this)
self.name=name #Construct attributes (like the cup Mold)
self.age=age

def __del__(self):#类的属性都一样(就是对象有相同的属性:如吃) 
    print(self .__class__.__name__+'name del') 
def eat(self):
    print(self .__class__ .__name__+'eat')
def move(self):
    print(self .__class__ .__name__ +'move') 

Encapsulation (property privatization——>provide methods to the outside, modify the properties) python is invalid in the module, valid in the class (the "__name" in the class is single underscore (private attribute, accessible), double underscore (private attribute, Inaccessible) there are underscores before and after (special attributes)

Inheritance (subclasses can access the properties of the parent class (provided that the parent class is public)
#define a class
1, python is a multiple inheritance implementation mechanism
2, if there are methods with the same name in multiple parent classes, the order of calling objects from the class
python2:
|--- new-style classes,
breadth-first inheritance
|---old-style classes (classic classes),
depth-first inheritance,
python3
only new-style classes

class Name(object ):#定义类,名称首字母大写,默认()里面为父类
#对象的构建(属性包括数据和方法)
    def __init__(self,name,age): #构造器构建实例(特殊方法)添加属性:名字,年龄(self为当前对象this)
        self.name=name    #构造属性(如同杯子的模具)
        self.age=age

    def __del__(self):#类的属性都一样(就是对象有相同的属性:如吃)
        print(self .__class__.__name__+'name del')
    def eat(self):
        print(self .__class__ .__name__+'eat')
    def move(self):
        print(self .__class__ .__name__ +'move')
    def sleep(self):
        print(self .__class__ .__name__ +'sleep')


class Person(Name ):#Persin继承Name(继承有属性,但有不同,有区分)
    #非绑定方法
    def __init__(self,name,age,sex):
        Name.__init__(self, name, age)  # 子类调用父类的构造方法
        self .sex=sex#多的属性区分父类
    def think(self):
        print(self .__class__ .__name__ +'think')
    def wear(self):
        print(self.__class__.__name__ + 'wear')
if __name__=='__main__':
    #a=Name('青蛙',2)#参考定义的构造器规划,实现对象的实例化
    #print('name=%s'%a.name )
    #print('age=%d'%a.age )

    #a.sleep()#aelp不需要传递,解释器自动完成
    #a.eat()
    #a.move()
    b=Person ('人',30,'男')#实例化对象
    print(b.name  )#自己独特的属性
    print(b.age )
    print(b.sex )
    b.eat()#继承的属性
    b.move()
    b.sleep() 

Overwrite|Override What is
the difference between override and overload?
(Overload: the function name is the same, the parameter type or number is different)

Overloading:
there is no overloading in function python

Polymorphism and inheritance
#define a class
class P(object):#define a class, the first letter of the name is capitalized, the default () is the parent class
#object construction (attributes include data and methods)

   def __init__(self,name,age):
       self.name=name
       self.age=age

   def run(self):
        print('P run...')

class C(P):
    def __init__(self,name,age,sex):
        P.__init__(self ,name,age )#传递父类的构造
        self. sex=sex

    def run(self):
        P.run(self ) #子类方法体调用父类方法
        print('C run...')#方法的覆盖
if __name__=='__main__':
  c=C('child',20,'man')

c.run()#Binding is the instantiated class, and no subclass can call the parent class. If the child class has it, it will not call the parent class (polymorphism)

dir () view class attributes

class A():
    '''
    this is a class
    '''
    def __init__(self):
        pass

if __name__=='__main__':
    for item in dir(A ):#将A放出来
        print(str (item )+str (getattr(A,item ) ) ) #

View class object properties

class A():
    '''
    this is a class
    '''
    def __init__(self,name):
        self .name=name

if __name__=='__main__':
    a=A('name')
    #print(dir(a ) )#查看类的属性和对象
    print(a .__dict__ )#查看对象属性
   

When the subclass has no method, the parent class is called

class P():
    #父类实现构造方法,实例化子类对象时会,调用父类的方法
   


 def __init__(self):
        print('p__e')

class A(P ):
    pass


if __name__=='__main__':
    a=A()
    

python父类如果实现了构造方法,子类没有,实例化子类对象时会默认调用父类的构造方法


```clike
class P():
 
    def __init__(self):
        print('P __init__ invoke...')
 
class A(P):
 
    def __init__(self):
        P.__init__(self)
        print('A __init__ invoke...')


 
 
if __name__ == '__main__':
    a=A()

  • Parent method calls multiple methods
 
 
class P1():
 
    def __init__(self):
        print('P1 __init__ invoke...')
 
class P2():
 
    def __init__(self):
        print('P2 __init__ invoke...')
 
class A(P1,P2):
 
    def __init__(self):
        P1.__init__(self)
        P2.__init__(self)
        print('A __init__ invoke...')
 
 
if __name__ == '__main__':
    a=A()

The second method super(A,self). init ()

 
 
class P1():
 
    def __init__(self):
        print('P1 __init__ invoke...')
 
class P2():
 
    def __init__(self):
        print('P2 __init__ invoke...')
 
class A(P2,P1):
    def __init__(self):
        P1.__init__(self)
        P2.__init__(self)
        super(A,self).__init__()
        print('A __init__ invoke...')
 
 
if __name__ == '__main__':
    a=A()
 
 
 
+ 静态方式无法访问对象的自身属性变量
 
```python
 
class A():
    method = 1  # 静态属性

    def __init__(self, name):
        self.name = name

    def run(self):
        print('run invoke...')

    @staticmethod
    def func(x):
        print('self.name=%s' % x)
        print('func invoke...')

    @classmethod
    def test(cls):
        print('test ...')
        print('method=%d'%A.method )#静态的查找


if __name__ == '__main__':
    # a=A('name')
    # a.run()
    # A.func('liwenbo')
    # A('xxx').func('yyy')
    A.test()

  • Method overload str
class A(object):
 
    def __init__(self,name,age):
        self.name=name
        self.age=age
 
    def __str__(self):#方法重载
        return 'name=%s,age=%d'%(self.name,self.age)
 
if __name__ == '__main__':
    a=A('liwen',20)
    print(a)
 
+ 重载__iter__和__next__实现一个可迭代的类型(无限循环的版本)
 

 

import random
 
class A():
 
    def __init__(self,seq):
        '''seq type(iterable)'''
        self.seq=seq
 
    def __iter__(self):
        return self#返回当前对象,变成可迭代的对象
 
    def __next__(self):
        return self.seq[random.randint(0,len(self.seq)-1)]
 
if __name__ == '__main__':
    a=A([1,2,3])
 
    for item in a:
        print(item)
 

Overload __iter__ and __next__ to implement an iterable type (limited loop version)

import random
 
class A():
 
    def __init__(self,seq):
        '''seq type(iterable)'''
        self.seq=seq
        self.index=0
 
    def __iter__(self):
        return self#返回当前对象
 
    def __next__(self):
        if self.index > len(self.seq) - 1:
            raise StopIteration
        else:
            tmp = self.seq[self.index]
            self.index+=1
            return tmp
 
if __name__ == '__main__':
    a=A([1,2,3,50,43])
 
    for item in a:
        print(item)
 
 
 
**单链表结构**
 
```python
 
#实现一个单链表
 
#用node来作为链表的节点抽象类

class Node():
 
    def __init__(self,data):
        self.data=data
        self.next=None
 
    def show(self):
        print('node data=%d'%self.data)
 
 
    def __str__(self):
        return 'node data=%s'%self.data
 
class LinkList():
 
    def __init__(self):
        self.head=None
 
    def insertFirst(self,data):
        newNode = Node(data)#创建新节点
        newNode.next=self.head
        self.head = newNode
 
    def deleteFirst(self):
        tmpNode= self.head
        self.head=self.head.next
        return tmpNode
 
    def travel(self):
        currentNode = self.head
        while currentNode is not None:
            print(currentNode)
            currentNode = currentNode.next
 
if __name__ == '__main__':
    n1=Node('A')
    n2=Node('B')
    n3=Node('C')
 
    link=LinkList()
    link.insertFirst(n1)
    link.insertFirst(n2)
    link.insertFirst(n3)
 
    link.travel()
 
    print('+'*30)
 
    link.deleteFirst()
    link.deleteFirst()
    link.deleteFirst()
 
    link.travel()

Subclass overrides the parent class to change the default behavior of the parent class

class Mr(dict ):#子类覆盖父类方法
    def keys(self):
        return sorted(super(Mr,self).keys(),reverse=False)#super父类方法调用

if __name__=='__main__':
        w=Mr({'a':1,'b':2})
        print(w.keys()) 

The child class inherits the immutable parent class (to change the immutable behavior of the parent class)

class WrapperFloat(float):#改变父类不可变变量,保留小数点后二位。
    def __init__(self,val):#禁止返回return
        self.val=val
        print('__init__')
      

    def __new__(cls,val):
        #return float.__new__(cls,round(val,2))
        return super(WrapperFloat, cls ).__new__(cls,round(val,2))#方法2
if __name__=='__main__':
    w=WrapperFloat(3.0098)
    print(w )
    

Slots application of the class (protection attribute)

class A():
    __slots__ = 'name','age'#定义了类的属性名称,不允许增加和修改

    def __init__(self,name):
        self.name=name
if __name__=='__main__':
    a=A('li')
    a.app()

Guess you like

Origin blog.csdn.net/weixin_47514459/article/details/109890624
Recommended