Nine, classes and instances

First, the basic concept of class

Is an abstract concept, can be understood as a collection of objects having the same attribute, attribute class, there are two

  • Properties (class definition variable, alias: static variables, static properties)
  • The method (function class definition Aliases: dynamic variables, dynamic properties)

实例It is a specific object class, the only instance of the operation attribute references.

1.1 Definition of the class

Animal (Animal) class, for example, Python provides the keyword class to declare a class:

class Animal(其他类名):
    pass

Where, Animal is the class name, class name is usually the first letter in upper case (if there is more than one word, each word is capitalized). If immediately followed (another class name), represent the class from some inherited class, all classes will inherit the default object class, but (object) by default do not write.

Each class has a method __dict__ default class attributes and methods may be presented in a form dictionary ( 属性展现格式,属性名:对应的值 方法名:对应的内存地址)

Generally used for all properties and methods query class, if the operation is a single dot properties and methods used by the universal single point change search class attributes and methods may be deletions

Examples of Class 1.2

Examples of a specific class of object can be obtained.

class Animal():
    pass

tiger = Animal()

When creating an instance, can also pass some parameters to initialize instances, to this end, we need to add a method __init__

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

tiger = Animal('t1') #实例化,创建具体的对象
print(tiger.name)

__init__ method is to initialize method instance, his first parameter is always self (refers to the instance itself), when creating the instance initialization method is invoked, passing parameters must correspond to the initialization method.

Instantiate an object total, there were three things:

  1. It opened up an object space in memory.
  2. __Init__ method is performed automatically in the class, and the object space (memory address) passed __init__ method first position parameter self.
  3. In the __init__ method add attributes to the object space through the self.

Relationship Class name space and object space
Here Insert Picture Description
From the figure we can expect that the object has been able to find the class attribute, because there is a pointer to the class object class namespace.

Find the object attribute order: first from object space to find ------> class space to find ------> parent space looking -------> ...

Find the class name attribute order: start looking for this type of space -------> -------- find the parent class space> ...

The above sequence is irreversible way, the class name can not find the object's properties.

1.3 class custom method

In addition to the class initialization method __init__ can also add custom methods.

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

    def greet(self):
        print('Hello, I am %s.' % self.name)

tiger = Animal('t1')
tiger.greet()

Custom class method, the first parameter which must also be self (pointing instance itself), these methods are extremely similar functions and built format.

The method of custom class may define an outer code block class definition, the class definition and reference code block, as follows:

def greet(self,y):
    print('Hello %s, I am %s'%(y,self.name))

class Animal():
    def __init__(self, name):
        self.name = name
    p=greet

tiger = Animal('t1')
tiger.p('bb')

Class method, another method may be cited in the same class, as follows

class Bag:
    def __init__(self):
        self.data = []

    def add(self, x):
        self.data.append(x)

    def addtwice(self, x):
        self.add(x)
        self.add(x)

1.4 portfolio

The encapsulated object class to an object of another class attribute, called combination.

class Gamerole:
    def __init__(self, name, ad, hp):
        self.name = name
        self.ad = ad
        self.hp = hp

    def equip_weapon(self, wea):
        self.wea = wea  # 组合:给一个对象封装一个属性改属性是另一个类的对象

class Weapon:
    def __init__(self, name, ad):
        self.name = name
        self.ad = ad

    def weapon_attack(self, p1, p2):
        p2.hp = p2.hp - self.ad - p1.ad
        print('%s 利用 %s 攻击了%s,%s还剩%s血'
              % (p1.name, self.name, p2.name, p2.name, p2.hp))

Class of private property

When the desired part of the class attribute (method) can be used only within the class can not be used outside the class and the derived class can define these properties (and methods) plus __, they will be classified as Class the private attributes (method), as follows

class Animal():
    def __init__(self, name):
        self.name = name
    __p='bb'


tiger = Animal('t1')
print(tiger.__p)
##AttributeError: 'Animal' object has no attribute '__p'

Second, the class inheritance

继承Is a way to create a new class, in python, the new class can inherit one or more parent classes, parent class can be called a base class or super class, the new class is called the derived class or subclass.

Subclasses inherit such properties of the parent class can be obtained (i.e., variables and functions that appear in the parent class)

2.1 single inheritance

Create a class, just inherit a parent, for example as follows

class A:
    def __init__(self,n):
        self.n=n

    def pri(self):
        print(self.n)

class B(A):
    pass

b=B(4) ##将b传给self,B类中没有__init__初始方法,但因为B类继承A类,就去A类中寻找初始化方法。b.n=4
b.pri()  ##B类中没有pri方法,只能继续在其父类A中寻找。

2.2 derived

Subclasses can also add your own new property or redefine these attributes (will not affect the parent class), once again define their own attributes and the same name as the parent class, then when you call the property, with regard to the subject himself.

class A:
    def __init__(self,n):
        self.n=n
    def pri(self):
        print(self.n)

class B(A):
    def pri(self):
        print(self.n**2)

b=B(4)      ##将b传给self,B类中没有__init__初始方法,但因为B类继承A类,就去A类中寻找初始化方法。b.n=4
b.pri()    ##在B类中有自己的方法,则使用子类自己的,输出得到16

super函数

class A:
    def __init__(self,n):
        self.n=n
    def pri(self):
        print(self.n)

class B(A):
    def __init__(self,n,name):
        super().__init__(n)  ##子类通过super方法,可接纳父类的方法为子类所使用,此处将父类的init方法作为自身init方法的一部分,
        self.name=name   ##子类自身再对init方法进行补充
    def pri(self):
        print(self.n**2,self.name)

b=B(4,"pks")
b.pri()

More than 2.3 inheritance

In the new class (new class python3 are all in), follow the principle of breadth-first, the order of succession can __mro__ get through the built-in function class.

class K1():
    def foo(self):
        print("K1-foo")

class K2():
    def foo(self):
        print("K2-foo")
    def bar(self):
        print("K2-bar")

class J1(K1, K2):
    pass

class J2(K1, K2):
    def bar(self):
        print("J2-bar")

class C(J1, J2):
    pass

if __name__ == "__main__":
    print(C.__mro__)
    m = C()
    m.foo()
    m.bar()

Python3 can be concluded from the above examples below Looking sequence
Here Insert Picture Description

Third, package type

For the object-oriented packages, in fact, it is to use the constructor (the __init__) encapsulation of the content object, and then packaged contents obtained indirectly or directly self through the object.

Fourth, class decorators

@property
Python's built-decorator ** ** @ property is responsible for a method disguised as property, call format and attributes called the method the same, but can not be modified unless re-direct references to other decorators.

from math import pi
class Circle:
    def __init__(self,r):
        self.r=r

    def per(self):   ##求周长
        return 2*pi*self.r

    @property
    def area(self):  ##使用装饰器,装饰类中的方法area,求面积
        return self.r**2*pi

c1=Circle(4)
print(c1.per())
print(c1.area)   ##装饰过的方法,可以像属性一样被调用,不用像方法一样加()进行调用

@ Method name .setter
** @ built-in Python method name .setter **, method of its decoration, it can achieve the same properties as the variable is assigned externally. Receiving incoming assignment processing method to be decorated.

class Person:
    def __init__(self,name,high,weight):
        self.name = name
        self.high = high
        self.weight = weight
    @property
    def bmi(self):
        return self.weight / self.high*2

    @bmi.setter             
    def bmi(self,n):    ##装饰器的格式:被装饰的方法名.setter  装饰过的方法,可以像类属性一样能在类的外部被调用进行修改。
         self.weight=n

jin = Person('金老板',1.6,90)
jin.bmi=32              ##呼应bmi.setter装饰的方法bmi  修改了类的属性weight为32
print(jin.bmi)          ##输出为40

@ Method name .deleter
@ Python built-in method name .deleter, the method of its decoration, to achieve external value can delete the class

class Person:
    def __init__(self,name,high,weight):
        self.name = name
        self.high = high
        self.weight = weight
    @property
    def bmi(self):
        return self.weight / self.high*2

    @bmi.deleter
    def bmi(self):    ##装饰器的格式:被装饰的方法名.deleter  装饰过的方法,可以想类属性一样能在类的外部进行删除。
        del self.weight

jin = Person('金老板',1.6,90)
print(jin.bmi)
print(jin.__dict__)
del jin.bmi         ##呼应bmi.deleter装饰过的方法  删除对象的weight属性
print(jin.__dict__)

@classmethod
Python built-in @classmethod, packing a function of class methods, the first parameter of the function must be cls, decorated methods outside the class can use the class name. Method call is completed

class Goods:
    __discount=0.8
    def __init__(self,name,price):
        self.name=name
        self.__price=price

    @property
    def price(self):
        return self.__price*Goods.__discount
    @classmethod  ##用于装饰某个方法,装饰过的方法在类的外部可以直接使用类名.方法进行调用,无需通过指定对象才能调用.
    def change_discount(cls,new_discount):  ##类方法 有一个默认参数 cls 代表这个类  cls
        cls.__discount=new_discount
apple=Goods('苹果',5)
print(apple.price)           #输出4.0
Goods.change_discount(0.5)   ##类名.方法  对应类中classmethod装饰过的方法,修改类的私有静态属性discount
print(apple.price)           #输出2.5

Application scenarios: when you want to operate the class attribute (such as modification, query), if the operation from an instance of the class, not logical this case can be used a method based @classmethod.

@staticmethod
Python built @staticmethod, and both objects do not have a relationship, and the class is not a function of the relationship between the decorative static method, a static method, that is to say, the operation does not involve the properties and methods of the class. Or without providing self cls parenthesis within the definition of the function. Can be called outside of class by class name Function name

class Login:
    def __init__(self,name,password):
        self.name = name
        self.pwd = password
    def login(self):pass

    @staticmethod
    def get_usr_pwd():   # 静态方法
        usr = input('用户名 :')
        pwd = input('密码 :')
        Login(usr,pwd)

Login.get_usr_pwd()

Fourth, the reflection type

Reflection: refers to a string, or a method to realize call object properties. Remember that everything is an object in python, the python reflected a very wide application

1, the reflection of the object

class A:
    age=29
    def hahaha(self):
        print('A')

a=A()
hasattr(a,"age")
print(a.age)    ##对象a的age属性
print(getattr(a,"age"))  ##对象a的age属性
a.hahaha()      ##对象a的hahaha方法
func=getattr(a,"hahaha")
func()   ##对象a的hahaha方法

2, the reflection of the class

class A:
    age=29
    def hahaha(self):
        print('A')

print(A.age)    ##29  类A的age属性
print(getattr(A,"age"))  ##29  类A的age属性
a=getattr(A,"hahaha")  ##类A的hahaha方法
a("2")   ##打印A

3, the reflection of this document

import sys

def s1():
    print('s1')

this_module = sys.modules[__name__]   #使用__name__保证this_module始终指向本文件,无论是自主运行还是被其他程序调用。
if hasattr(this_module, 's1'):
    getattr(this_module, 's1')()  

4, the reflection of the other modules

import test2

test2.test2()
a=getattr(test2,"test2")
a()

Reflecting the actual use case
prior solution did not learn reflection

class User:
    def login(self):
        print('欢迎来到登录页面')
    
    def register(self):
        print('欢迎来到注册页面')
    
    def save(self):
        print('欢迎来到存储页面')


while 1:
    choose = input('>>>').strip()
    if choose == 'login':
        obj = User()
        obj.login()
    
    elif choose == 'register':
        obj = User()
        obj.register()
        
    elif choose == 'save':
        obj = User()
        obj.save()

After learning solutions reflection

class User:
    def login(self):
        print('欢迎来到登录页面')
    
    def register(self):
        print('欢迎来到注册页面')
    
    def save(self):
        print('欢迎来到存储页面')

user = User()
while 1:
    choose = input('>>>').strip()
    if hasattr(user,choose):
        func = getattr(user,choose)
        func()
    else:
        print('输入错误。。。。')
Published 40 original articles · won praise 2 · Views 2062

Guess you like

Origin blog.csdn.net/weixin_42155272/article/details/93999645