Python3 Object-oriented

Source: Internet
Author: User
Tags function definition

Python3 Object-oriented

Python is an object-oriented language, with a sentence in Python: Everything is an object

Introduction to Object Orientation
    • Class: Used to describe a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
    • Class variables: Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.
      • Data members: Class variables or instance variables are used to manipulate the data related to the class and its instance objects.
      • Method overrides: If the method inherited from the parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method, also known as the override of the method.
      • Instance variable: A variable defined in a method that acts only on the class of the current instance.
      • Inheritance: A derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of type dog is derived from the animal class, which is the analog "is a (is-a)" Relationship (example, dog is a animal).
      • Instantiation: Creates an instance of a class, the concrete object of the class.
      • Method: A function defined in a class.
      • Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods. Definition of Class

        The syntax format is as follows:

class ClassName:    <statement-1>    .    .    .    <statement-N>

After a class is instantiated, its properties can be used; in fact, after a class is created, its properties can be accessed through the class name.

Class object

The class object supports two operations: Property Reference and instantiation.
Attribute reference syntax: Obj.name
After an object is created, all the names in the class namespace are valid property names

#!/usr/bin/python3class People:    """一个人类"""    def __init__(self, name, age):    # 类的初始化方法,实例化的时候首先调用的方法,前后双下划线的方法都是特殊方法        self.name = name              # 类的属性,也是特点、特征        self.age = age    def walk(self):                  # 普能方法        """人类会走路"""        print(f‘{self.name} is walking‘)# 实例化p = People(‘yhyang‘, 18)# 访问类的属性和方法print(f‘我的名字是:{p.name},我今年{p.age}岁‘)p.walk()输出:我的名字是:yhyang,我今年18岁yhyang is walking

Note: In the example above,init() is the initialization method for the class that initializes the properties and methods in the class.

    • Self represents an instance of a class, not a class
    • There is only one special difference between a method of a class and a normal function--they must have an extra first parameter name, according to the Convention its name is self.
    • Self represents an instance of a class that represents the address of the current object, while Self.class points to a class. Methods of the class

      Within a class, using the DEF keyword to define a method, unlike a generic function definition, a class method must contain the parameter self, and for the first argument, self represents an instance of the class.
      Example code:

#!/usr/bin/python3class People:    """一个人类"""    def __init__(self, name, age):    # 类的初始化方法,实例化的时候首先调用的方法,前后双下划线的方法都是特殊方法        self.name = name              # 类的属性,也是特点、特征        self.age = age    def walk(self):                  # 普能方法        """人类会走路"""        print(f‘{self.name} is walking‘)# 实例化p = People(‘yhyang‘, 18)# 访问类的方法p.walk()输出:yhyang is walking
Variables in a class
    • Private variable: __name, cannot be inherited
    • Internal variable: _ Start
    • Protect data by modifying private data through methods
      Example code:
#!/usr/bin/python3class car:name = ' xxx ' # class properties Def __init__ (self, brand, pric E, Wheels, power): Self._brand = Brand Self.price = Price Self.wheels = Wheels Self.power = PO            Wer self.__speed = 0 def run (Self, Action): print (f ' {Self.brand} is running ') if action = = ' 1 ':    Self.__speed + = 1 * 10 # Modify the private variable print (' current speed: {}/h '. Format (self.__speed))                                       def start: print (f ' {Self.brand} is on ') @property def speed (self):                                          # read-only, getter Method return Self.__speed @property def brand: Return Self._brand @brand. Setter # Add Setter method, can be assigned Def brand (self, brand): If not isinstance (brand, str)                                : Raise TypeError (' brand is String type ') # raise throws Exception Self._brand = Brand # You can manipulate the property to determine the @prop in advanceErty # Turn the function below into a property that can be used directly with the instance name. Info to call Def info (self): return f ' {SE Lf.brand}: {self.price} ' # Instantiation auto = Car (' Auto ', 30000, 4, ' oil ') auto.run (' 1 ') # Call the Run () method, modify the private variable Auto.info # to access the info () method by accessing the property Auto.brand = ' AudiA8 ' # this Brand is not a property, but a brand method defined at the bottom of the @brand.setter Auto.brandtesla = Car (' Tesla ', 100000, 4, ' Electric ') tesla.run (' 1 ') Tesla.price = 999999 # Here is the property of the class object tesla.pricetesla.nameCar.nameauto.country = ' China ' # Dynamic new declaration of a property in the object of the class, no auto in the original class . Country output: Auto is running current speed is: ten km/h ' auto:30000 ' audiA8 ' Tesla is running current speed is: ten km/h999999 ' xxx ' xxx ' ' China '
Special methods
  • init: Bind various attributes to self
  • Slots: Restricting dynamic properties of instances, reducing memory consumption, type tuple
  • STR: Descriptive text for an object
  • eq: Compare Objects for equality
  • Classmethod and Staticmethod; Classmethod will pass the class itself as the first argument
    Example code 1:

    #!/usr/bin/python3class Computer:__slots__ =(‘__name‘, ‘mem‘, ‘cpu‘)  # 为节省资源,不允许实例对象随意添加属性def __init__(self, name, mem, cpu):    self.__name = name    self.mem = mem    self.cpu = cpudef play(self, game=‘qq games‘):    print(‘play‘,game)# 实例化pc2 = Computer(‘admin‘, ‘8G‘, ‘8核‘)pc2.mempc2.ssd = ‘ssd‘  # 此处会报错,类中用了__slots__所以不能随意添加输出:‘8G‘AttributeError: ‘Computer‘ object has no attribute ‘ssd‘

    Example code 2:

    #!/usr/bin/python3class Computer:__slots__ =(‘_name‘, ‘mem‘, ‘cpu‘)  # 为节省资源,不允许实例对象随意添加属性def __init__(self, name, mem, cpu):    self._name = name    self.mem = mem    self.cpu = cpudef play(self, game=‘qq games‘):    print(‘play‘,game)def __str__(self):                 # 当print(对象)时,自动调用此方法    return f‘{self._name}:{self.mem}-{self.cpu}‘# 实例化pc3 = Computer(‘admin‘, ‘8G‘,‘8核‘)print(pc3)                       # 直接打印对象输出:admin:8G-8核

    Example Code 3:

    #!/usr/bin/python3class Computer:__slots__ =(‘_name‘, ‘mem‘, ‘cpu‘)  # 为节省资源,不允许实例对象随意添加属性def __init__(self, name, mem, cpu):    self._name = name    self.mem = mem    self.cpu = cpudef play(self, game=‘qq games‘):    print(‘play‘,game)def __str__(self):                 # 当print(对象)时,自动调用此方法    return f‘{self._name}:{self.mem}-{self.cpu}‘def __eq__(self,other):              # 对象A == 对象B 时调用    return self.cpu == other.cpu# 实例化pc2 = Computer(‘admin‘,‘8G‘,‘8核‘)pc3 = Computer(‘admin‘,‘4G‘,‘8核‘)pc2 == pc3                               # 调用__eq__方法,认为cpu相等即为两个对象相等输出:True

    Example Code 4:

    #!/usr/bin/python3class Computer:__slots__ =(‘_name‘, ‘mem‘, ‘cpu‘)  # 为节省资源,不允许实例对象随意添加属性def __init__(self, name, mem, cpu):    self._name = name    self.mem = mem    self.cpu = cpudef play(self, game=‘qq games‘):    print(‘play‘,game)def __str__(self):                 # 当print(对象)时,自动调用此方法    return f‘{self._name}:{self.mem}-{self.cpu}‘def __eq__(self,other):              # 对象A == 对象B 时调用    return self.cpu == other.cpu@classmethoddef new_pc(cls, info):            #cls 相当于类本身,通过 类名.new_pc(‘参数’)来直接生成实例,而不调用__init__    "从字符串直接产生新的实例"    name, mem, cpu = info.split(‘-‘)  # 传参时用-连接三个参数    return cls(name, mem, cpu)# 使用classmethod建立新对象pc666 = Computer.new_pc(‘yhyang-16G-8eeeee核‘)print(pc666)输出:yhyang:16G-8核

    Example code 5:

    #!/usr/bin/python3class Computer:__slots__ =(‘_name‘, ‘mem‘, ‘cpu‘)  # 为节省资源,不允许实例对象随意添加属性def __init__(self, name, mem, cpu):    self._name = name    self.mem = mem    self.cpu = cpudef play(self, game=‘qq games‘):    print(‘play‘,game)def __str__(self):                 # 当print(对象)时,自动调用此方法    return f‘{self._name}:{self.mem}-{self.cpu}‘def __eq__(self,other):              # 对象A == 对象B 时调用    return self.cpu == other.cpu@classmethoddef new_pc(cls, info):            #cls 相当于类本身通过 类名.new_pc(‘参数’)来直接生成实例,而不调用__init__    "从字符串直接产生新的实例"    name, mem, cpu = info.split(‘-‘)  # 传参时用-连接三个参数    return cls(name, mem, cpu)@staticmethod   # 不需要生成类的实例,就可以使用的方法 ,直接用 类名.calc来调用此方法def calc(a,b,oper): # 不用第一个参数    "根据操作符+-*/来计算a 和b的结果"    if oper == ‘+‘:        return a + bComputer.calc(2,5,‘+‘)输出:7
    Three characteristics of object-oriented
  • Packaging
  • Inherited
  • Polymorphic

    Inheritance (multiple inheritance for the time being)

    Python supports the inheritance of classes in the following format:

    class DerivedClassName(BaseClassName1):<statement-1>...<statement-N>

    Note the order of the base classes in parentheses, if the base class has the same method name, and if the subclass is not specified when it is used, the python left-to-right search is the method that finds the base class from left to right when it is not found in the subclass.

Baseclassname (the base class name in the example) must be defined within a scope with the derived class. In addition to classes, you can also use expressions, which are useful when a base class is defined in another module:
Class Derivedclassname (ModName. Baseclassname):
Example code:

#!/usr/bin/python3#类定义class people:    #定义基本属性    name = ‘‘    age = 0    #定义私有属性,私有属性在类外部无法直接进行访问    __weight = 0    #定义构造方法    def __init__(self,n,a,w):        self.name = n        self.age = a        self.__weight = w    def speak(self):        print("%s 说: 我 %d 岁。" %(self.name,self.age))#单继承示例class student(people):    grade = ‘‘    def __init__(self,n,a,w,g):        #调用父类的构函        people.__init__(self,n,a,w)        self.grade = g    #覆写父类的方法    def speak(self):        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))s = student(‘ken‘,10,60,3)s.speak()输出:ken 说: 我 10 岁了,我在读 3 年级
Method Overrides (Polymorphic)
    • If the functionality of your parent's method does not meet your needs, you can override the methods of your parent class in subclasses
    • The super () function is a method for calling the parent class (the superclass).
      Example code:
#!/usr/bin/python3class Parent:        # 定义父类   def FatherMethod(self):      print (‘调用父类方法‘)class Child(Parent): # 定义子类   def FatherMethod(self):      print (‘调用子类方法‘)c = Child()          # 子类实例c.FatherMethod()         # 子类调用重写方法super(Child,c).FatherMethod() #用子类对象调用父类已被覆盖的方法输出:调用子类方法调用父类方法
Meta-programming
    • The type of the class is the Type,type type is the meta-type metaclass, and the type of the object is the class type
    • Order type---> class-----> Object
    • Class A inherits from type, and returns an object through the new method of type, which can be considered an object of Class A, so
    • Class is instantiated by a = A (), in fact A is the return value of the new method in a call type
      Example code 1:
#!/usr/bin/python3# 运行时动态创建类和函数# metaclass -> class ->obj# __new__class Game:    passGame.__class__输出:typetype(Game)输出:type

Example code 2:

#!/usr/bin/python3# type 是一个metaclass# 通过type创建一个新的metaclassclass Yuhy(type):    passclass Yhy(metaclass=Yuhy):    passprint(type(Yuhy))       # 查看Yuhy类的类型print(type(Yhy))         # 查看Yhy类的类型输出:<class ‘type‘><class ‘__main__.Yuhy‘>isinstance(Yhy,Yuhy)      # Yhy与Yuhy是否是同样的类型输出:True

Use Yhy.__new__? this method to view
Signature:yhy.__new__ (*args, **kwargs)
Docstring:create and return a new object. See Help (type) for accurate signature.
Type:builtin_function_or_method
help(type)
Example code:

class Yuhy(type):    def __new__(cls, name, bases, my_dict):   # classmethod        print(f‘{name} 使用__new__创建‘)        yhy = super().__new__(cls, name, bases, my_dict)        return yhyclass Ks(metaclass=Yuhy):    pass输出:Ks 使用__new__创建a = Ks()print(a)输出:<__main__.Ks object at 0x0000024AF06E9A20>
What can reflection be used for?

Reflection is also called introspection, in fact, let the object tell us what he has, what he can do
There are three ways of

    • Hasattr (obj,attr)
    • SetAttr (Obj,attr,val)
    • GetAttr (obj,attr)
      Example code 1:
#!/usr/bin/python3# hasattr(obj, attr) 检查obj是否有一个名为attr的值的属性,返回一个bool# getattr(obj,attr) 检查obj中是否有attr属性或方法,并将其返回# setattr(obj,attr,value)  向对象obj中添加一个属性,值为values = ‘yhyang‘                   # s是一个字符串对象s.upper()输出:‘YHYANG‘isinstance(s, str)输出:Truehasattr(s,‘upper‘)    # 查看s当中是否有一个叫upper的方法输出:True

Example code 2:

#!/usr/bin/python3class People:    def eat(self):        print(‘eate‘)    def drink(self):        print(‘drink‘)p = People()p.eat()hasattr(p,‘eat‘)  # 找这个对象p中有没有eat这个方法getattr(p,‘eat‘) # 在p中找到eat方法 并返回aa = getattr(p,‘eat‘)aa()setattr(p, ‘sleep‘, ‘sleep1234‘)     # 添加一个新的属性,值为sleep1234p.sleep输出:eateTrue<bound method People.eat of <__main__.People object at 0x0000024AF06F7668>>eate‘sleep1234‘

Example code 3: Car Factory

#!/usr/bin/python3# 汽车类class Car:    def info(self):        print(‘Car 父类 ‘)class Audi(Car):    def info(self):        print(‘Audi 汽车‘)class Tesla(Car):    def info(self):        print(‘Tesla 汽车‘)# 工厂类class Factory:    def create(self):        print(‘创建汽车,工厂基类‘)class AudiFactory(Factory):    def creat(self):        print(‘创造Audi汽车‘)        return Audi()class TeslaFactory(Factory):    def creat(self):        print(‘创造Tesla汽车‘)        return Tesla()# 生产汽车audi_F = AudiFactory()audi = audi_F.creat()audi.info()#另一种写法AudiFactory().creat().info()TeslaFactory().creat().info()输出:创造Audi汽车Audi 汽车创造Audi汽车Audi 汽车创造Tesla汽车Tesla 汽车

Python3 Object-oriented

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.