All data in Python is in the form of an object, and the object is an instance of the class.Defining classes (Class)Use class to define a class.For example, define a cat class, as follows:class Cat ():def __init__ (self): self.name = nameCreate an instance of the two cat class Cat1,cat2, as follows:CAT1 == Cat (' Momo ')The __init__ in the class is an initialization function that executes when the instanc
I. Definition and use of classes
Python defines a basic syntax for a class:
Copy the Code code as follows:Class ClassName ([base class one, base class two ...]):
[Def __init__ (self, [agv1,agv2 ...]):] # define Constructorsdef method1 (self, [agv1,agv2 ...]): # member function
For use:
object instance name = Class Name (parameter list)
object instance name. member function name (parameter list)
differ
the first parameter of a method is a class object, not an instance object.
By convention, the first parameter of a class method is named the CLS. It is not necessary to define class methods at any time (the functions that can be implemented by a class method can be implemented by defining a common function, as long as the function accepts a class object as a parameter).
Define class methods and use class methods:
Copy Code code as follows:
Class Abase (object):
@classmethod #类
Object-oriented concepts are classes (class) and instances (Instance), and it is important to keep in mind that classes are abstract templates, such as student classes, and instances are specific "objects" that are created from classes, each with the same method, but the data may be different for each object.Still taki
Python implements the programming of object-oriented (object-oriented programming, or OOP) by using classes (Class) and objects (object). The main purpose of object-oriented programming is to improve the reuse of the program, which is similar to the purpose of the function.One: functionIf you need to reuse code in your program,---------define the function. def function name (parameter)://todoSuch as:Output:
class. Data in ClassclassTurtle:def __init__(self,x): Self.num=xclassFISHL:def __init__(self,x): Self.num=xclassPool:def __init(self,x,y): Self.turtle=Turtle (x) #把T中数据调入self. Turtle, Self.turtle.num self.fish can be used=Fish (y) #实例. Transfer into class. Data in ClassdefPrint_num (self):Print("turtle%d, small fish%d"% (Self.turtle.num,self.fish.num))Mix-inReproducedclassWeapon:defPrick (self, obj):#This is the device's active skill to kill each other .Obj.life_value-= 500#Assuming that the at
variable names that are defined in Python) here, the private variables are emphasized, and Python's default member functions and member variables are public, and there are no modifiers such as public,private in other similar languages. However, you can add two underscore "_" to the variable before In this case, the function or variable becomes private. This is Python's private variable rolling (this translation is very awkward), English is (private n
after the execution:>>> A.kick () I'm the ball A, why are you kicking me? >>> B.kick () I'm ball B, why are you kicking me? >>> C.kick () I'm ball C, why are you kicking me? 1.2 The Magic method in Python:Python's objects are inherently magical, and they are all about Python for the object, and they are a special way to add magic to your class, and if your object implements one of these methods, the method is called by
It's a special use in Python to see a variable or function name like __slots__ such as __xxx__.
__slots__ we already know how to use it, the __len__ () method is also known to allow class to function in the Len () function.
In addition, there are many special-purpose functions in Python's class that can help us customize our classes.
__str__
Let's first define a student class and print an instance:
This article mainly introduces the differences between super () and _ init _ () in the python class. This article is very detailed and has some reference value, you can refer to the functions implemented by super () and _ init _ () when inheriting a ticket.
class Base(object):def __init__(self):print 'Base create'class childA(Base):def __init__(self):print 'creat A ',Base.__init__(self)class childB(Base):def __init__(self):print 'creat B ',super(chi
According to the "Principle of Everything" in Python, all created objects are the result of a known class instantiation, and which class is instantiated by? First look at the following piece of codeClass Foo (object): passobj = Foo () print type (obj) print type (Foo) result is: As you can see: obj is instantiated by foo, and Foo is created by the type classSo foo can do this, look at the following:def func: print "charles" Foo = Type (' Foo ',
We are familiar with the basic concepts of objects and classes. We will further expand so that we can actually use objects and classes.
Calling additional information for the class
As mentioned in the previous note, when defining a method, you must have the self parameter. This parameter represents an object. Object has all the properties of a class, we can invoke the Class property through self.
The code
method, at least with the self parameter.
5. Initialize instances include: Define and initialize instance properties: Or invoke some methods of the class.
6. The construction method can carry various parameters except self (keyword parameter, default parameter, collect parameters with tuple, collect keyword parameters in dictionary, etc.); When you instantiate a class, you pass in the specified value for the corresponding property.
Program Demo:
Washb.pyclass Washer: def init (self,water=10
comparison)Automated Operational RoadmapPython-developed Speaker Introduction:Linux OPS master lecturer old boyThe old boy Linux training founder, senior Linux cluster actual combat architecture expert, 51CTO expert, judge. Engaged in the first-line operation and maintenance of the framework of practical and educational training experience 14 years. Good at large-scale Linux cluster architecture details, the old boy lectures to grasp the focus, emphasis on ideas and practical skills, pay specia
): = p = qP and q are integers, which represent rational number p/q.If you want rational to perform a + operation, you need to implement __add__ correctly:classRational (object):def __init__(self, p, q): SELF.P=P SELF.Q=Qdef __add__(self, R):returnRational (SELF.P * r.q + self.q * R.P, SELF.Q *r.q)def __str__(self):return '%s/%s'%(SELF.P, SELF.Q)__repr__=__str__Now you can try the rational number addition:>>> r1 = Rational (1, 3)>>> r2 = rational (1, 2)print r1 + R25/65. type conv
') get_coach_data (' Julie2.txt ') ========== RESTART: c:/users/eric/documents/python/kelly/kelly2.py ==========sarAh Sweeney ' s fastest times are:[' 2.18 ', ' 2.21 ', ' 2.22 ']james Lee ' s fastest times are:[' 2.01 ', ' 2.16 ', ' 2.22 ']mikey McManus ' s fastest times are:[' 2.22 ', ' 2.31 ', ' 2.38 ']julie Jones ' s fastest times are:[' 2.11 ', ' 2.23 ', ' 2.59 '3. Add 2 new methods to the athlete class and call the testdef senitize (time_string)
For Python, everything is an object, and objects are created based on class columns such as Name= ' Csdcs ' li=[1,3,43] above two are objects, because they are all in the Python class there are many functions, the collection of functions, the object is stored with the specific input values, With the memory address of the class when the object is going to perform different functions, it will look for the fun
The examples in this article describe methods for using static variables in Python classes and functions. Share to everyone for your reference. The specific analysis is as follows:
The use of static variables in Python classes and functions (including the lambda method) seems to be something that is not possible [is i
""" the Note: The above example can only present the encapsulated features. About here are just some of the things I've summed up, simple, don't want to get too complicated . the object-oriented has three basic characteristics: encapsulation, inheritance, polymorphism the encapsulation: is to say that objective things encapsulated into abstract class, and some untrusted class hidden information the inheritance: Primarily for code reuse. + Polymorphic : Py
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.