Summary of Python Object Oriented Member Knowledge

  • 2021-11-13 08:14:41
  • OfStack

1. Membership

1.1 Variables

Instance variables belong to objects, and each object maintains its own data. Class variables, which belong to classes and can be shared by all objects, are generally used to provide common data to objects (similar to global variables).

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        # message = "{}-{}-{}".format(Person.country, self.name, self.age)
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
 
p1 = Person(" Huaqing water ",20)
print(p1.name)
print(p1.age)
print(p1.country) #  China 
 
p1.show() #  China - Huaqing water -20

Tip: When you put the same sample variable that exists in every object, you can choose to put it in the class variable, which can avoid maintaining multiple identical data in the object.

Error-prone point

Pay attention to the difference between reading and writing.

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
Person.country = " United States "
 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  United States 
Read and write in inheritance relationship

class Base(object):
    country = " China "
 
 
class Person(Base):
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(Person.country, self.name, self.age)
        # message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
 
#  Read 
print(Base.country) #  China 
print(Person.country) #  China 
 
obj = Person(" Huaqing water ",19)
print(obj.country) #  China 
 
#  Write 
Base.country = "china"
Person.country = " Thailand "
obj.country = " Japan "

1.2 Methods

Binding method, by default, has 1 self parameter, which is called by the object (self is equal to the object calling the method at this time) "Object & Class can call " Class method, which has 1 cls parameter by default, and can be called by class or object (cls is equal to the class that calls the method at this time) "Object & Class can call " Static method, no default parameters, can be called with both classes and objects. "Object & Class can call "

class Foo(object):
 
    def __init__(self, name,age):
        self.name = name
        self.age = age
 
    def f1(self):
        print(" Binding method ", self.name)
 
    @classmethod
    def f2(cls):
        print(" Class method ", cls)
 
    @staticmethod
    def f3():
        print(" Static method ")
        
#  Bind method (object) 
obj = Foo(" Wu Peiqi ",20)
obj.f1() # Foo.f1(obj)
 
 
#  Class method 
Foo.f2()  # cls Is the class that is currently calling this method. (Class) 
obj.f2()  # cls Is the class of the object that is currently calling this method. 
 
 
#  Static method 
Foo.f3()  #  Class executes execution methods (classes) 
obj.f3()  #  Object executes the execution method 

In Python, it is flexible, and methods can be called through objects and classes. In java, c # and other languages, binding methods can only be called by objects. Class methods or static methods can only be called by classes.


import os
import requests
 
 
class Download(object):
 
    def __init__(self, folder_path):
        self.folder_path = folder_path
 
    @staticmethod
    def download_dou_yin():
        #  Download Tik Tok 
        res = requests.get('.....')
 
        with open("xxx.mp4", mode='wb') as f:
            f.write(res.content)
 
    def download_dou_yin_2(self):
        #  Download Tik Tok 
        res = requests.get('.....')
        path = os.path.join(self.folder_path, 'xxx.mp4')
        with open(path, mode='wb') as f:
            f.write(res.content)
 
 
obj = Download("video")
obj.download_dou_yin()

1.3 Attributes

Attributes are actually created from a combination of binding methods and special decorators, so that we can call methods later without parentheses.


class Foo(object):
 
    def __init__(self, name):
        self.name = name
 
    def f1(self):
        return 123
 
    @property
    def f2(self):
        return 123
 
 
obj = Foo(" Huaqing water ")
 
v1 = obj.f1()
print(v1)
 
v2 = obj.f2
print(v2)

class Pagination:
    def __init__(self, current_page, per_page_num=10):
        self.per_page_num = per_page_num
        
        if not current_page.isdecimal():
            self.current_page = 1
            return
        current_page = int(current_page)
        if current_page < 1:
            self.current_page = 1
            return
        self.current_page = current_page
	
    def start(self):
        return (self.current_page - 1) * self.per_page_num
	
    def end(self):
        return self.current_page * self.per_page_num
 
 
user_list = [" Users -{}".format(i) for i in range(1, 3000)]
 
#  Display in pages, each page 10 Article 
while True:
    page = input(" Please enter the page number: ")
	
    # page The page number currently visited 
    # 10 , displayed per page 10 Bar data 
	#  Internal execution Pagination Class init Method. 
    pg_object = Pagination(page, 20)
    
    page_data_list = user_list[ pg_object.start() : pg_object.end() ]
    for item in page_data_list:
        print(item)

class Pagination:
    def __init__(self, current_page, per_page_num=10):
        self.per_page_num = per_page_num
 
        if not current_page.isdecimal():
            self.current_page = 1
            return
        current_page = int(current_page)
        if current_page < 1:
            self.current_page = 1
            return
        self.current_page = current_page
 
    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num
 
    @property
    def end(self):
        return self.current_page * self.per_page_num
 
 
user_list = [" Users -{}".format(i) for i in range(1, 3000)]
 
#  Display in pages, each page 10 Article 
while True:
    page = input(" Please enter the page number: ")
 
    pg_object = Pagination(page, 20)
    page_data_list = user_list[ pg_object.start : pg_object.end ]
    
    for item in page_data_list:
        print(item)

There are two ways to write attributes:

Mode 1, based on decorator

class C(object):
    
    @property
    def x(self):
        pass
    
    @x.setter
    def x(self, value):
        pass
    
    @x.deleter
    def x(self):
		pass
        
obj = C()
 
obj.x
obj.x = 123
del obj.x
Mode 2, based on definition variables

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
0

Note: Because attributes and instance variables are called in the same way, you should be careful when writing: attribute names do not duplicate instance variables.


class Foo(object):
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    @property
    def func(self):
        return 123
 
 
obj = Foo(" Huaqing water ", 123)
print(obj.name)

If you have the same name, you may report an error.


class Foo(object):
 
    def __init__(self, name, age):
        self.name = name  #  Report an error, mistakenly thinking that you want to call  @name.setter  The method of decoration. 
        self.age = age
 
    @property
    def name(self):
        return "{}-{}".format(self.name, self.age)
 
 
obj = Foo(" Huaqing water ", 123)

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
3

If you really want to create 1 relationship on the name, you can have the instance variable underlined.


class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
4

2. Member modifiers

The modifiers of members in Python refer to public and private.

Public, you can call this member anywhere. Private, change members can only be called inside the class (if a member begins with two underscores, it means that the member is private).

class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
5

Special reminder: Private members in the parent class cannot be inherited by subclasses.


class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
6

class Base(object):
 
    def __data(self):
        print("base.__data")
 
    def num(self):
        print("base.num")
        self.__data()  #  Execution of private methods in parent class is not allowed 
 
 
class Foo(Base):
 
    def func(self):
        self.num()
 
 
obj = Foo()
obj.func()

It stands to reason that private members cannot be called externally, but if you use 1 special syntax, you can also write this way in Flask source code, and you don't recommend writing this way).


class Foo(object):
 
    def __init__(self):
        self.__num = 123
        self.age = 19
 
    def __msg(self):
        print(1234)
 
 
obj = Foo()
print(obj.age)
print(obj._Foo__num)
obj._Foo__msg()

Whether members can be exposed to the outside world as independent functions, which can be called and used by the outside world.

Yes, it's public. No, the other internal put 1 auxiliary, private.

3. Object nesting

When programming based on object-oriented, there can be various relationships between objects, such as composition, association, dependence, etc. (called in Java), which is nested in vernacular.

Scenario 1:


class Person(object):
    country = " China "
 
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
    def show(self):
        message = "{}-{}-{}".format(self.country, self.name, self.age)
        print(message)
 
print(Person.country) #  China 
 
p1 = Person(" Huaqing water ",20)
print(p1.name) #  Huaqing water 
print(p1.age) # 20
print(p1.country) #  China 
p1.show() #  China - Huaqing water -20
 
p1.name = "root"     #  In the object p1 Chinese speaking name Reset to root
p1.num = 19          #  In the object p1 Add instance variables in  num=19
p1.country = "china" #  In the object p1 Add instance variables in  country="china"
 
print(p1.country)   # china
print(Person.country) #  China 
9

Scenario 2:


class Student(object):
    """  Student category  """
 
    def __init__(self, name, age, class_object):
        self.name = name
        self.age = age
        self.class_object = class_object
 
    def message(self):
        data = " I am 1 Name {} Class, my name is :{}, I am this year {} Years old ".format(self.class_object.title, self.name, self.age)
        print(data)
 
 
class Classes(object):
    """  Class class  """
 
    def __init__(self, title):
        self.title = title
 
 
c1 = Classes("Python Full stack ")
c2 = Classes("Linux Cloud computing ")
 
 
user_object_list = [
    Student(" Huaqing water ", 19, c1),
    Student(" All roads lead to Rome ", 19, c1),
    Student(" Spring flower and autumn moon--seasonal views ", 19, c2)
]
 
for obj in user_object_list:
    print(obj.name,obj.age, obj.class_object.title)

Scenario 3:


class Student(object):
    """  Student category  """
 
    def __init__(self, name, age, class_object):
        self.name = name
        self.age = age
        self.class_object = class_object
 
    def message(self):
        data = " I am 1 Name {} Class, my name is :{}, I am this year {} Years old ".format(self.class_object.title, self.name, self.age)
        print(data)
 
 
class Classes(object):
    """  Class class  """
 
    def __init__(self, title, school_object):
        self.title = title
        self.school_object = school_object
 
 
class School(object):
    """  School class  """
 
    def __init__(self, name):
        self.name = name
 
 
s1 = School(" Beijing campus ")
s2 = School(" Shanghai campus ")
 
c1 = Classes("Python Full stack ", s1)
c2 = Classes("Linux Cloud computing ", s2)
 
user_object_list = [
    Student(" Huaqing water ", 19, c1),
    Student(" All roads lead to Rome ", 19, c1),
    Student(" Spring flower and autumn moon--seasonal views ", 19, c2)
]
for obj in user_object_list:
    print(obj.name, obj.class_object.title ,  obj.class_object.school_object.name)

4. Special members

There are 1 special methods in the class of Python, which are __方法__ Format, this method has special meanings internally. Next, let's talk about some common special members:

__init__ The initialization method

class Foo(object):
    def __init__(self, name):
        self.name = name
 
 
obj = Foo(" Huaqing water ")
__new__ The construction method

class Foo(object):
    def __init__(self, name):
        print(" No. 1 2 Step: Initialize the object and create data in the empty object ")
        self.name = name
 
    def __new__(cls, *args, **kwargs):
        print(" No. 1 1 Step: Create an empty object and return ")
        return object.__new__(cls)
 
 
obj = Foo(" Huaqing water ")
__call__

class Foo(object):
    def __call__(self, *args, **kwargs):
        print(" Execute call Method ")
 
 
obj = Foo()
obj()
__str__

class Foo(object):
 
    def __str__(self):
        return " Ha ha ha ha "
 
 
obj = Foo()
data = str(obj)
print(data)
__dict__

class Foo(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
 
obj = Foo(" Huaqing water ",19)
print(obj.__dict__)
__getitem__ , __setitem__ , __delitem__

class Foo(object):
 
    def __getitem__(self, item):
        pass
 
    def __setitem__(self, key, value):
        pass
 
    def __delitem__(self, key):
        pass
 
 
obj = Foo(" Huaqing water ", 19)
 
obj["x1"]
obj['x2'] = 123
del obj['x3']
__enter__ , __init__0

class Foo(object):
 
    def __enter__(self):
        print(" Into ")
        return 666
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(" Out ")
 
 
obj = Foo()
with obj as data:
    print(data)

# Interview questions (supplementary code to achieve the following functions)


class Context:
 
    def __enter__(self):
        return self        
 
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass
 
    def do_something(self):      # __enter__ Return self You can call the execution do_something Method 
        pass
 
 
with Context() as ctx:
    ctx.do_something()

The above interview questions belong to context-managed syntax.

__add__ Etc

class Foo(object):
    def __init__(self, name):
        self.name = name
 
    def __add__(self, other):
        return "{}-{}".format(self.name, other.name)
 
 
v1 = Foo("alex")
v2 = Foo("sb")
 
#  Object + Value, it will be executed internally   Object .__add__ Method and set the + The following values are passed as parameters. 
v3 = v1 + v2
print(v3)
__iter__

Iterator


#  Definition of iterator type: 
    1. When the class defines the  __iter__  And  __next__  Two methods. 
    2.__iter__  Method needs to return the object itself, that is: self
    3. __next__  Method, returning the following 1 If there is no data, you need to throw 1 A StopIteration The exception of. 
	 Official documents: https://docs.python.org/3/library/stdtypes.html#iterator-types
        
#  Create   Iterator type   : 
	class IT(object):
        def __init__(self):
            self.counter = 0
 
        def __iter__(self):
            return self
 
        def __next__(self):
            self.counter += 1
            if self.counter == 3:
                raise StopIteration()
            return self.counter
 
#  Create from class instantiation 1 Iterator objects: 
    obj1 = IT()
    
    # v1 = obj1.__next__()
    # v2 = obj1.__next__()
    # v3 = obj1.__next__() #  Throw an exception 
    
    v1 = next(obj1) # obj1.__next__()
    print(v1)
 
    v2 = next(obj1)
    print(v2)
 
    v3 = next(obj1)
    print(v3)
 
 
    obj2 = IT()
    for item in obj2:  #  Object of the iterator object is executed first __iter__ Method and get the return value, 1 Go straight to repeated execution  next( Object ) 
        print(item)    

The iterator object supports taking value through next, and automatically throws StopIteration if the value is finished.

In the for loop, the __iter__ method is executed first to obtain an iterator object, and then the value of next is continuously executed (if there is an exception, the loop will be terminated).

Generator


#  Create a generator function 
    def func():
        yield 1
        yield 2
    
#  Create a generator object (internally based on the generator class generator The object created), the inside of the generator class also declares: __iter__ , __next__  Method. 
    obj1 = func()
    
    v1 = next(obj1)
    print(v1)
 
    v2 = next(obj1)
    print(v2)
 
    v3 = next(obj1)
    print(v3)
 
 
    obj2 = func()
    for item in obj2:
        print(item)

According to the iterator regulations, the generator class is actually a special iterator class (the generator is also a special iterator in one).

Iterable object


#  If 1 Among the classes are __iter__ Method and returns the 1 Iterator objects   ; Then we call the object created with this class an iterable object. 
 
class Foo(object):
    
    def __iter__(self):
        return  Iterator object ( Generator object )
    
obj = Foo() # obj Yes   Iterable objects. 
 
#  Iterable objects are objects that can be used for To loop, in the interior of the loop, it is actually executed first  __iter__  Method, get its iterator object, and then internally execute the iterator object's next Function, step by step value. 
for item in obj:
    pass

Iterable objects can use for to loop. In fact, in the interior of the loop, __iter__ method is executed first to obtain its iterator object, and then the next function of this iterator object is executed internally to take values step by step.


class IT(object):
    def __init__(self):
        self.counter = 0
 
    def __iter__(self):
        return self
 
    def __next__(self):
        self.counter += 1
        if self.counter == 3:
            raise StopIteration()
        return self.counter
 
 
class Foo(object):
    def __iter__(self):
        return IT()
 
 
obj = Foo() #  Iterable object 
 
 
for item in obj: #  When the loop can iterate an object, the internal executes first obj.__iter__ And get the iterator object; Constantly executes the iterator object's next Method. 
    print(item)

#  Based on iterative objects & Iterator Implementation: Custom range
class IterRange(object):
    def __init__(self, num):
        self.num = num
        self.counter = -1
 
    def __iter__(self):
        return self
 
    def __next__(self):
        self.counter += 1
        if self.counter == self.num:
            raise StopIteration()
        return self.counter
 
 
class Xrange(object):
    def __init__(self, max_num):
        self.max_num = max_num
 
    def __iter__(self):
        return IterRange(self.max_num)
 
 
obj = Xrange(100)
 
for item in obj:
    print(item)

class Foo(object):
    def __iter__(self):
        yield 1
        yield 2
 
 
obj = Foo()
for item in obj:
    print(item)

#  Based on iterative objects & Generator   Implementation: Custom range
 
class Xrange(object):
    def __init__(self, max_num):
        self.max_num = max_num
 
    def __iter__(self):
        counter = 0
        while counter < self.max_num:
            yield counter
            counter += 1
 
 
obj = Xrange(100)
for item in obj:
    print(item)

Common data types:


from collections.abc import Iterator, Iterable
 
v1 = [11, 22, 33]
print( isinstance(v1, Iterator) )  # false Judging whether it is an iterator; The judgment is based on __iter__  And  __next__ . 
v2 = v1.__iter__()
print( isinstance(v2, Iterator) )  # True
 
 
 
v1 = [11, 22, 33]
print( isinstance(v1, Iterable) )  # True The judgment is based on whether there is  __iter__ And returns an iterator object. 
 
v2 = v1.__iter__()
print( isinstance(v2, Iterable) )  # True The judgment is based on whether there is  __iter__ And returns an iterator object. 

At this point, Python Advanced Object-Oriented members of the summary, if there are any inadequacies welcome to correct.


Related articles: