Detailed Explanation of Class Object Sample in Python

  • 2021-10-16 02:04:28
  • OfStack

Abstract characteristics

Based on the concept of Python 1 all objects, the class class has the following characteristics:

Properties of classes and instances

Class object creation optionally defines class attributes. When an instance object is created, the instance attributes automatically initialize the __init__ method of the class

The instance object automatically inherits the corresponding class attribute, if any, but the instance attribute takes precedence

Parameters of instance method, class method and static method

The instance method is a generic function, but the instance method needs to pass in the self parameter (different from the generic function)

Class methods and static methods are functions implemented through decorators. Class methods need to pass in cls parameters, while static methods do not need to pass in self parameters or cls parameters (but they can also pass in parameters)

Where the self parameter must point to the instance object, and the cls parameter must point to the defined class object (self and cls are conventional, and other names can be used in principle)

Methods and Functions

Method is a function in the context of object. Instance calls instance method is called method, and class calls instance method is called function

Specific details

Class example


class Toy(object): #  Here, this class can be understood as designing 1 A Toy Blueprint of 
  #  Assign values to define class attributes and record the number of all toys 
  count = 0

  def __init__(self, name): #  Used for instance initialization 
    self.name = name
    #  Class attribute  +1
    Toy.count += 1

  @classmethod #  This decorator is represented as a class method, which can be called without creating an instance object, and is the most flexible 
  def show_toy_count(cls):
    print(' Number of toy objects  %d' % cls.count, cls)

  @staticmethod #  This decorator representation is a static method, which is essentially a function encapsulated in a class object and is often used to test 
  def hi():
    print('Hello!')

  #  Instance method 
  def beybey(self):
    print('Sad ! ', self)


#  Create an instance object 
toy1 = Toy(' Lego ')
toy1.hand = 2
toy2 = Toy(' Teddy bear ')
toy3 = Toy(' Godzilla ')
print(toy1.name, toy2.name, toy3.name)

#  Point syntax calls class methods and static methods, such as class names . Method 
Toy.show_toy_count()
Toy.hi()
#  When an instance object calls a class method, it is the same as when a class object calls a class method, but it actually calls a class object that is still inherited through the instance object 
toy1.show_toy_count()
print(toy1.hand)
#  When an instance object calls a static method, it is the same as when a class object calls a static method, but actually calls a class object that is still inherited through the instance object 
toy2.hi()
#  Instance object calls instance method ,Python Inside the interpreter of, when we call toy3.beybey() When, in fact, Python Interpret as Toy.beybey(toy3)
toy3.beybey()
# Toy.beybey() #  Wrong syntax, self Must point to an instance object, where the instance method points to a class object instead of an instance object 
Toy.beybey(toy3)
#  The type and memory address of the class and its instances 
print(type(Toy), id(Toy), type(toy3), id(toy3))

Output result

Lego Teddy Bear Godzilla
Number of toy objects 3 < class '__main__.Toy' >
Hello!
Number of toy objects 3 < class '__main__.Toy' >
2
Hello!
Sad! < __main__.Toy object at 0x000001FD9F794D60 >
Sad! < __main__.Toy object at 0x000001FD9F794D60 >
< class 'type' > 2188806599664 < class '__main__.Toy' > 2188813880672

Examples of class methods and static methods


class Cat: #  Or class Cat() Class objects are defined in the form of parent objects, and ancestors are inherited by default object Object 
  name = ' Xiaomin '

  @classmethod
  def www(cls):
    print('%s  What! ' % cls.name)
    # cls.call() #  Class methods can call static methods 

  @staticmethod
  def call():
    print(' Meow meow ~ ')
    Cat.name = ' Xiaomin smelly brother '
    print(Cat.name)
    # Cat.www() #  Static methods can call class methods 


Cat.www()
Cat.call()
#  There is no instance method defined to create instance object inheritance and use the methods in it 
cat1 = Cat()
cat1.www()
cat1.call()

Output result

What's Xiaomin doing!
Meow meow ~
Xiaomin smelly brother
Xiaomin smelly brother!
Meow meow ~
Xiaomin smelly brother

Basic methods contained in ancestor objects


print(dir(object))

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Summarize

Class class is the core object in Python. To define a class, it is usually necessary to write several parts such as class attributes, instance methods, class methods and static methods. The class and the instances of the inherited class are compared to the main function and sub-function in the function, then the class attribute can be regarded as global variable, and the instance attribute can be regarded as local variable; Taking the class as a gourd, the example method is convenient for us to follow the picture and provide the possibility of adapting to local conditions; The class approach enables us to use the functions of classes more efficiently, while static methods often help us understand the functions of classes.

The methods of class are not irrelevant to each other, but have strong commonness, so they should be used flexibly and should not be limited to abstract definitions.


Related articles: