Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of getting started with object-oriented Python

2025-02-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "Python object-oriented case analysis". In daily operation, I believe many people have doubts about Python object-oriented case analysis. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "Python object-oriented case analysis". Next, please follow the editor to study!

Both object-oriented programming and functional programming (process-oriented programming) are programming methods, but there is a slight difference.

Process-oriented programming:

1. Import various external libraries

two。 Design various global variables

3. Write a function to complete a function

4. Write a function to complete a function

5. Write a function to complete a function

6. Write a function to complete a function

7. Write a function to complete a function

8..

9. Write a main function as a program entry

In multi-function programs, many important data are placed in the global data area so that they can be accessed by all functions. Each function can have its own local data, and encapsulate some functional code into the function, so that there is no need to repeat writing in the future, only the function can be called. From the point of view of the organization of the code, it is based on the business logic from top to bottom.

Object-oriented programming:

1. Import various external libraries

two。 Design various global variables

3. Decide which class you want

4. Provide a complete set of operations for each class

5. Explicitly use inheritance to show what different classes have in common

6. Decide whether or not to write a main function as a program entry as needed

In object-oriented programming, functions and variables are further encapsulated into classes, which are the basic elements of the program, which closely links data and operations, and protects the data from being accidentally changed by external functions. The instance of class and class (also called object) is the core concept of object-oriented, which is the fundamental difference from process-oriented programming and functional programming.

You don't have to use object-oriented programming, it depends on how your program is designed, but for now, it's basically object-oriented programming.

The basic usage of the class

Object-oriented is defined by defining the class class, so object-oriented programming only uses the class class, there are encapsulation, inheritance functions in the class class, and you can also construct the parameters to be passed in for easy control.

Case one: import sys

Import time

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class studetn:

# define a class named studetn

Def _ init__ (self,idx):

# define initialization constructions. Init is used here, and other attributes such as reversed,iter are also used.

Self.idx=idx

# initialize variables to facilitate inheritance

Def runx (self):

# define the running function and inherit variables from it

Print self.idx

# print out the value of idx, or do something else

Time.sleep (1)

A=studetn ('a')

A.runx ()

# this is the call of the class, be sure to remember the method of using the class, first pass in the parameters, and the class assigns a value to the variable a

# then call the function defined below this class

Some technical terms and concepts, since there is a high-end definition of object-oriented programming, it is natural to match some high-end concepts.

1. Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. The object is called an instance of the class.

2. Example: also called object. Through the initialization method defined by the class, the concrete value is given to become a "flesh and blood entity".

Instantiation: the process or operation of creating an instance of a class.

4. Instance variable: the variable defined in the instance acts only on the current instance.

5. Class variables: class variables are common to all instances. Class variables are defined in the class, but outside the method body.

6. Data members: a general term for class variables, instance variables, methods, class methods, static methods and attributes.

Method: the function defined in the class.

8. Static methods: methods that can be executed by a class without instantiation

9. Class methods: class methods are methods that operate on the class itself as an object.

10, method rewriting: if the method inherited from the parent class can not meet the needs of the subclass, you can rewrite the method of the parent class, this process is also known as override.

11. Encapsulation: wraps the internal implementation, makes it transparent to the outside, and provides a mechanism for calling api interfaces

Inheritance: that is, a derived class (derived class) inherits the variables and methods of the parent class (base class).

13. Polymorphism: it is processed in different ways according to the type of object.

Class and instance #-*-coding: utf-8-*-

# @ Time: 2018-5-3 0003 17:02

# @ Author: Langzi

# @ Blog: www.langzi.fun

# @ File: object-oriented 2.py

# @ Software: PyCharm

Import sys

Import time

Import requests

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class cc:

Ccc = 'ccc'

# cc is the class name. If you want to inherit another class, class cc (threading) means inheriting from threading.

Def _ init__ (self,a,b,c):

Self.a=a

Self.b=b

Self.c=c

# the process of defining construction is instantiation

Def runx (self):

Print self.a*10

Print self.b*5

Print self.c*2

Def runy (self):

Print requests.get ('http://www.langzi.fun').headers

E = cc ('AAA','CCC','EEE')

E.runx ()

E.runy ()

# these two are the methods in the calling class

Print e.c

# instance variables refer to the variables owned by the instance itself. The variables for each instance are different in memory.

Print e.ccc

# Class variable, find the defined variable in the class. Call the three method instance methods of the class #-*-coding: utf-8-*-

# @ Time: 2018-5-3 0003 17:16

# @ Author: Langzi

# @ Blog: www.langzi.fun

# @ File: object-oriented 3.py

# @ Software: PyCharm

Import sys

Import time

Import requests

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class dd:

Def _ init__ (self,url):

Self.url=url

Def runx (self):

Print requests.get (self.url). Status_code

A = dd ('http://www.langzi.fun')

A.runx ()

# this kind of calling method is the instance method static method

Static methods are called by the class and have no default parameters. Remove the self from the instance method parameters and add @ staticmethod to the method definition to become a static method. It belongs to the class and has nothing to do with the instance. It is recommended to use only class names. The way static methods are called. (although you can also use an instance name. Static method invocation)

#-*-coding: utf-8-*-

# @ Time: 2018-5-3 0003 17:21

# @ Author: Langzi

# @ Blog: www.langzi.fun

# @ File: object-oriented 4.py

# @ Software: PyCharm

Import sys

Import requests

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class ff:

@ staticmethod

Def runx ():

Print requests.get ('http://www.langzi.fun').status_code

Ff.runx ()

# here, the variables of the class are called directly, and the methods that run only in the class but not in the instance are called

There are often functions related to classes that require static methods at run time without the participation of instances and classes. Static methods can be used, such as changing environment variables or modifying properties of other classes. This situation can be solved directly with functions, but it also diffuses the code within the class, making it difficult to maintain.

Class method

Class methods are called by the class, decorated with @ classmethod, and pass at least one cls parameter (which refers to the class itself, similar to self). When a class method is executed, the class that calls the method is automatically assigned to cls. It is recommended to use only class names. The way the class method is called. (although you can also use an instance name. Method of the class)

Actual case

If you want to construct a class, accept a site and its status code, and then print it out. It's like this:

Import sys

Import requests

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class gg:

Def _ init__ (self,url,stat):

Self.url=url

Self.stat=stat

Def outer (self):

Print self.url

Print self.stat

A = gg ('langzi',200)

A.outer ()

This is to use the instance method, although it can be implemented, but sometimes the parameter passed in is not in the format ('langzi',200), but rather (' langzi-200'). What should I do? First of all, you need to split this, but it is troublesome to implement it using instance methods, so you can use class methods at this time.

#-*-coding: utf-8-*-

# @ Time: 2018-5-3 0003 17:27

# @ Author: Langzi

# @ Blog: www.langzi.fun

# @ File: object-oriented 5.py

# @ Software: PyCharm

Import sys

Import requests

Reload (sys)

Sys.setdefaultencoding ('utf-8')

Class gg:

Url = 0

Stat = 0

# because new variables are passed in after using classmethod, you need to define class variables first.

Def _ init__ (self,url=0,stat=0):

# here is the constructor according to the normal definition

Self.url=url

Self.stat=stat

@ classmethod

# decorator, execute the following function immediately

Def split (cls,info):

# this function takes two arguments. The default cls is the init function of this class, and info is passed in from the outside.

Url,stat=map (str,info.split (-'))

# this is converted to a formatted structure

Data = cls (url,stat)

# then execute the first method of the class, and the class constructor needs to pass in two parameters, so two parameters are passed in

Return data

# the function result is returned directly here

Def outer (self):

Print self.url

Print self.stat

R = gg.split (('langzi-200'))

R.outer ()

# here is the invocation class method, which is the same as calling the instance method.

Encapsulation means that the implementation code of data and specific operations is placed inside an object and cannot be accessed externally. The class's method must be called before it can be started.

Case class cc:

Ccc = 'ccc'

# cc is the class name. If you want to inherit another class, class cc (threading) means inheriting from threading.

Def _ init__ (self,a,b,c):

Self.a=a

Self.b=b

Self.c=c

Print e.ccc

# Class variable, find the defined variable in the class.

Print ccc

# error will be reported here, this is encapsulation. The functions in the class are the same. Inherit

When we define a class, we can inherit from an existing class, the new class is called a subclass (Subclass), and the inherited class is called a base class, parent class, or superclass (Base class, Super class). For example, we have written a class called Animal, and there is a run () method that can print directly:

Class Animal (object):

Def run (self):

Print 'Animal is running...'

When we need to write Dog and Cat classes, we can inherit directly from the Animal class:

Class Dog (Animal):

Pass

Class Cat (Animal):

Pass

What are the benefits of inheritance? The biggest benefit is that the subclass gets all the functionality of the parent class. Because Animial implements the run () method, Dog and Cat, as its subclasses, automatically have the run () method without doing anything:

Dog = Dog ()

Dog.run ()

Cat = Cat ()

Cat.run ()

When both the subclass and the parent class have the same run () method, we say that the run () of the subclass overrides the run () of the parent class, and the run () of the subclass is always called when the code runs. In this way, we get another benefit of inheritance: polymorphism.

Polymorphisms

To understand the benefits of polymorphism, we also need to write another function that accepts a variable of type Animal:

Def run_twice (animal):

Animal.run ()

Animal.run ()

When we pass in an instance of Animal, run_twice () prints out:

Run_twice (Animal ())

Running result:

Animal is running...

Animal is running...

When we pass in an instance of Dog, run_twice () prints out:

Run_twice (Dog ())

Running result:

Dog is running...

Dog is running...

When we pass in an instance of Cat, run_twice () prints out:

Run_twice (Cat ())

Running result:

Cat is running...

Cat is running...

It doesn't seem interesting, but if you think about it, now, if we define another Tortoise type, it also derives from Animal:

Class Tortoise (Animal):

Def run (self):

Print 'Tortoise is running slowly...'

When we call run_twice (), pass in the instance of Tortoise:

Run_twice (Tortoise ())

Running result:

Tortoise is running slowly...

Tortoise is running slowly...

You will find that adding a subclass of Animal does not have to make any changes to run_twice (). In fact, any function or method that relies on Animal as an argument can work without modification, because of polymorphism.

The advantage of polymorphism is that when we need to pass in Dog, Cat, Tortoise... We only need to accept the Animal type, because Dog, Cat, Tortoise... They are all Animal types, and then you can operate according to the Animal type. Because the Animal type has a run () method, any type passed in, as long as it is an Animal class or subclass, will automatically call the run () method of the actual type, which means polymorphism:

For a variable, we only need to know that it is an Animal type, and we can safely call the run () method without knowing exactly its subtype, and whether the specific run () method acts on the Animal, Dog, Cat or Tortoise object, which is determined by the exact type of the object at run time, this is the real power of polymorphism: the caller only calls, regardless of the details, and when we add a subclass of Animal Just make sure that the run () method is written correctly, regardless of how the original code is called. This is the famous "opening and closing" principle:

Open to extensions: new Animal subclasses are allowed

Closed to modification: there is no need to modify functions such as run_twice () that depend on the Animal type.

Conclusion: inheritance can directly take all the functions of the parent class, so that there is no need to start from zero, the subclass only needs to add its own unique methods, and it can also overwrite the methods that are not suitable for the parent class; only with inheritance can there be polymorphism. When calling class instance methods, try to treat variables as parent class types so that all subclass types can be accepted normally; the old way of defining Python classes allows you not to inherit from object classes, but this programming method is seriously deprecated. Whenever there is no appropriate class to inherit, it inherits from the object class.

Magic method

It is mentioned above that there are other methods of iter,reverse in addition to _ _ init__. Here we will explain in detail what other methods are available in addition to init initialization.

_ _ init__: constructor, called when the object is generated

_ _ del__: destructor, used when releasing objects

_ _ repr__: print, convert

_ _ setitem__: assign values according to index

_ _ getitem__: gets the value by index

_ _ len__: get length

_ _ cmp__: comparison operation

_ _ call__: call

_ _ add__: addition operation

_ _ sub__: subtraction operation

_ _ mul__: multiplication

_ _ div__: division operation

_ _ mod__: remainder operation

Specific use of _ _ pow__: power

1. _ _ doc__

Illustrative documents and information. Python self-built, no need to customize.

Class Foo:

"description class information, which can be collected automatically"

Def func (self):

Pass

# print the documentation for the class

Print (Foo.__doc__)

2. _ _ init__ ()

Instantiate a method that automatically triggers execution when an instance is created through a class.

Class Foo:

Def _ _ init__ (self, name):

Self.name = name

Self.age = 18

Obj = Foo ('jack') # automates the _ _ init__ method in the class

3. _ module__ and _ class__

Module indicates which module the object of the current operation belongs to. Class indicates which class the object of the current operation belongs to. These two are also built-in in Python and do not need to be customized.

Class Foo:

Pass

Obj = Foo ()

Print (obj.__module__)

Print (obj.__class__)

Running result: main

4. _ _ del__ ()

The destructor method, which is automatically triggered when the object is released in memory.

Note: this method generally does not need to be customized, because Python has its own memory allocation and release mechanism, unless you need to specify some actions during release. The call to the destructor is automatically triggered by the interpreter during garbage collection.

Class Foo:

Def _ del__ (self):

Print ("I've been recycled!")

Obj = Foo ()

Del obj

5. _ _ call__ ()

If the method is written for a class, the method can be called by adding parentheses to the instance of the class.

Note: the execution of the constructor is performed by the class with parentheses, that is, the object = the class name (), while for the call () method, it is triggered by the parenthesis after the object, that is, object () or class () ()

Class Foo:

Def _ init__ (self):

Pass

Def _ _ call__ (self, * args, * * kwargs):

Print ('_ _ call__')

Obj = Foo () # execute _ _ init__

Obj () # execute _ _ call__

You can test with Python's built-in callable () function to determine whether an object can be executed.

Callable (Student ())

Running result:

True

6. _ _ dict__

List all members of a class or object! A very important and useful attribute, Python self-built, does not need to be user-defined.

Class Province:

Country = 'China'

Def _ _ init__ (self, name, count):

Self.name = name

Self.count = count

Def func (self, * args, * * kwargs):

Print ('func')

# get the members of the class

Print (Province.__dict__)

# get the members of the object obj1

Obj1 = Province ('HeBei',10000)

Print (obj1.__dict__)

# get the members of the object obj2

Obj2 = Province ('HeNan', 3888)

Print (obj2.__dict__)

7. _ _ str__ ()

If the str () method is defined in a class, the return value of that method is output by default when printing the object. This is also a very important method that needs to be defined by the user.

In the following class, no str () method is defined, and the printed result is:

Class Foo:

Pass

Obj = Foo ()

Print (obj)

After defining the _ _ str__ () method, the printed result is: 'jack'.

Class Foo:

Def _ str__ (self):

Return 'jack'

Obj = Foo ()

Print (obj)

8. _ _ getitem__ (), _ _ setitem__ (), _ _ delitem__ ()

To take, assign, and delete the "three Musketeers" routine, we have seen it many times in Python, such as the previous @ property decorator.

In Python, identifiers are followed by parentheses, which usually means to execute or invoke a method. The identifier is followed by brackets [], which usually represents the meaning of the value. Python designs three special members, getitem (), setitem (), and delitem (), to perform actions related to square brackets. They represent values, assignments, and deletions of data, respectively.

That is, to do the following:

A = identifier []: execute the _ _ getitem__ method

Identifier [] = a: execute the _ _ setitem__ method

Del identifier []: execute the _ _ delitem__ method

If a class defines these three magic methods at the same time, the instance of the class behaves like a dictionary, as shown in the following example:

Class Foo:

Def _ _ getitem__ (self, key):

Print ('_ _ getitem__',key)

Def _ _ setitem__ (self, key, value):

Print ('_ _ setitem__',key,value)

Def _ _ delitem__ (self, key):

Print ('_ _ delitem__',key)

Obj = Foo ()

Result = obj ['K1'] # automatically triggers execution _ _ getitem__

Obj ['k2'] =' jack' # automatically triggers execution _ _ setitem__

Del obj ['K1'] # automatically triggers execution of _ _ delitem__

9. _ _ iter__ ()

This is the iterator method! Lists, dictionaries, and tuples can do for loops because the method iter () is defined internally. If the user wants the object of the custom class to be iterated, then the method needs to be defined in the class and the return value of the method is an iterable object. This iter () method of the class is called when you use the for loop to traverse the object in your code.

Ordinary classes:

Class Foo:

Pass

Obj = Foo ()

For i in obj:

Print (I)

# error report: TypeError: 'Foo' object is not iterable

# the reason is that the Foo object cannot be iterated

Add a _ _ iter__ (), but return nothing:

Class Foo:

Def _ iter__ (self):

Pass

Obj = Foo ()

For i in obj:

Print (I)

# error report: TypeError: iter () returned non-iterator of type 'NoneType'

# the reason is that the _ _ iter__ method does not return an iterable object

Return one iterative object after another:

Class Foo:

Def _ _ init__ (self, sq):

Self.sq = sq

Def _ iter__ (self):

Return iter (self.sq)

Obj = Foo ([11, 22, 3, 44)

For i in obj:

Print (I)

The best way is to use the generator:

Class Foo:

Def _ init__ (self):

Pass

Def _ iter__ (self):

Yield 1

Yield 2

Yield 3

Obj = Foo ()

For i in obj:

Print (I)

10. _ _ len__ ()

In Python, if you call the built-in len () function to try to get the length of an object, in the background, you are actually calling the object's len () method, so the following code is equivalent:

Len ('ABC')

three

'ABC'.__len__ ()

three

Python's list, dict, str and other built-in data types all implement this method, but your custom class needs to be well designed to implement the len method.

11. _ _ repr__ ()

This method works much like str (), except that str () returns the string seen by the user, while repr () returns the string seen by the program developer, that is, repr () is for debugging. Usually the two codes are the same.

Class Foo:

Def _ _ init__ (self, name):

Self.name = name

Def _ str__ (self):

Return's "this is" self.name

_ _ repr__ = _ _ str__

12. _ _ add__: addition operation _ _ sub__: subtraction operation _ _ mul__: multiplication operation _ _ div__: division operation _ _ mod__: remainder operation _ _ pow__: power operation

These are all arithmetic operations, and you need to design your own specific operation code for the class. Some Python built-in data types, such as int, come with these methods. Python supports operator overloading, that is, overriding.

Class Vector:

Def _ _ init__ (self, a, b):

Self.a = a

Self.b = b

Def _ str__ (self):

Return 'Vector (% d,% d)'% (self.a, self.b)

Def _ add__ (self,other):

Return Vector (self.a + other.a, self.b + other.b)

V1 = Vector (2jue 10)

V2 = Vector (5Jing Murray 2)

Print (v1 + v2)

13. _ _ author__ author information

_ _ author__ = "Jack"

Def show ():

Print (_ _ author__)

Show ()

14. _ _ slots__

As a dynamic language, Python can continue to add a random number or any type of variables or methods to the class or object after the class definition is completed and instantiated, which is the characteristic of dynamic language. For example:

Def print_doc (self):

Print ("")

Class Foo:

Pass

Obj1 = Foo ()

Obj2 = Foo ()

# add instance variables dynamically

Obj1.name = "jack"

Obj2.age = 18

# dynamically add instance methods to classes

Foo.show = print_doc

Obj1.show ()

Obj2.show ()

But! What if I want to limit the variables that an instance can add? You can have slots restrict the variables of an instance, for example, by allowing only instances of Foo to add name and age attributes.

Def print_doc (self):

Print ("")

Class Foo:

_ _ slots__ = ("name", "age")

Pass

Obj1 = Foo ()

Obj2 = Foo ()

# add instance variables dynamically

Obj1.name = "jack"

Obj2.age = 18

Obj1.sex = "male" # this sentence will pop up an error

# but you cannot restrict adding methods to a class

Foo.show = print_doc

Obj1.show ()

Obj2.show ()

Since 'sex' is not in the list of _ _ slots__, the sex property cannot be bound. Trying to bind sex will get the error of AttributeError.

Traceback (most recent call last):

File "F:/Python/pycharm/201705/1.py", line 14, in

Obj1.sex = "male"

AttributeError: 'Foo' object has no attribute' sex'

It is important to note that the properties defined by slots work only on instances of the current class, not on subclasses that inherit it. If you inherit a parent class and somehow find that some variables cannot be defined, isn't that a big problem? If unnecessary subclasses are also restricted, unless slots is also defined in the subclass, the properties that the subclass instance is allowed to define are its own slots plus the parent class's slots.

Member protection and access mechanism

There are some objects you don't want to access externally, even by calling class objects, so please finish this chapter carefully.

Private member class obj:

Def _ init__ (self,name):

Self.name=name

Def pri (self):

Print self.name

_ _ age = 18

# what is double underlined is a private variable, which can only be accessed inside the class, but not externally.

A = obj ('zhao')

A.pri ()

Running result:

Zhao

If you want to call this private member in a class, you can use the

Class obj:

Def _ init__ (self,name):

Self.name=name

Def prin (self):

Print self.name

_ _ age = 18

# what is double underlined is a private variable, which can only be accessed inside the class, but not externally.

@ classmethod

# if you want to call in a class, call the class method first

Def pri (cls):

Print cls.__age

# and then use

A = obj ('zhao')

A.prin ()

Obj.pri ()

# by calling private variables in the class directly in this way

Running result:

Zhao

18 use the get-set-del method to operate the private member class obj:

Def _ init__ (self,name):

Self.name=name

Def prin (self):

Print self.name

_ _ age = 18

# what is double underlined is a private variable, which can only be accessed inside the class, but not externally.

@ classmethod

# if you want to call in a class, call the class method first

Def pri (cls):

Print cls.__age

# and then use

@ classmethod

Def set_age (cls,value):

Cls.__age = value

Return cls.__age

The usage of # is to change the value of _ _ age

@ classmethod

Def get_age (cls):

Return cls.__age

# this usage is to directly return the value of _ _ age

@ classmethod

Def del_age (cls):

Del cls.__age

# this usage is to directly delete the value of _ _ age

Print obj.get_age ()

# here, the value directly called _ _ age returns a value of 18.

Print obj.set_age (20)

# here is to directly change the value of _ _ age and return a value of 20

Obj.del_age ()

# here is the value of directly deleting _ _ age

Think about it: since it is a private variable and does not allow external access, why should it be called and changed later? Because private variables can be extra detected, processed, processed, and so on. For example, judge the value of value, use isinstance and then do if-else judgment.

Private variables can be used to protect internal variables, which cannot be changed externally, but can be detected and processed.

Here, we extend the protection mechanism of private members. Use _ _ age to protect private variables like-> obj._obj__age. To put it bluntly, you can directly call the internal private variable age by using obj._obj__age.

Propety decorator

The way to disguise the method of a class as a property call is to change a function in the class into something like an attribute. At first, the method of the class is called in parentheses, but now it is read and stored by the property. Give an example to illustrate:

The common calling method class obj:

Def _ init__ (self,name,age):

Self.__name=name

Self.__age=age

# set these to private variables

Def get_age (self):

Return self.__age

Def set_age (self,value):

If isinstance (value,int):

Self.__age=value

Else:

Raise ValueError ('non-integer type')

Def del_age (self):

Print 'delete over'

A = obj ('langzi',18)

Print a.get_age ()

A.set_age (20)

Print a.get_age () uses the decorator class obj:

Def _ init__ (self,name,age):

Self.__name=name

Self.__age=age

# set these to private variables

@ property

Def age (self):

Return self.__age

@ age.setter

Def age (self,value):

If isinstance (value,int):

Self.__age=value

Else:

Raise ValueError ('non-integer type')

@ age.deleter

Def age (self):

Print 'delete over'

A = obj ('langzi',18)

# using these decorators, you can call directly using the methods of classes and objects

Print a.age

# here is the value returned by calling age directly

A.age=20

# here is to convert values directly using setter

Print a.age

Del a.age

# Delete age

Of course, this kind of calling method is a bit troublesome, each time is to go to the instance class and object, there is a more simple and intuitive method.

Use the property () function to halve it

In addition to using a decorator to disguise a method as a property, the property () function in Python's built-in builtins module provides us with a second way to set class properties.

Class People:

Def _ _ init__ (self, name, age):

Self.__name = name

Self.__age = age

Def get_age (self):

Return self.__age

Def set_age (self, age):

If isinstance (age, int):

Self.__age = age

Else:

Raise ValueError

Def del_age (self):

Print ("Delete age data!")

# the core is in this sentence

Age = property (get_age, set_age, del_age, "age")

Obj = People ("jack", 18)

Print (obj.age)

Obj.age = 19

Print ("obj.age:", obj.age)

Del obj.ag

A method is disguised as an attribute through the statement age = property (get_age, set_age, del_age, "age"). The effect is the same as that of the decorator.

The arguments to the property () function:

The first parameter is the method name, calling the instance. The method that is automatically executed when the

The second parameter is the method name, calling the instance. Method that executes automatically when attribute = XXX

The third argument is the method name, which calls the del instance. The method that is automatically executed when the

The fourth parameter is the string, which calls the instance. Description information when attribute. _ _ doc__. At this point, the study of "Python object-oriented introductory case Analysis" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report