In python, common objects are used as Dictionary classes (dict ).
Currently, I know two methods:
1. The defined class inherits the dict class.
For example
Class A (dict): pass
A = ()
A ['name'] = 12
2. Add a custom class
_ Setitem _ () _ getitem _ () method
Class A: def _ init _ (self, cfg = {}):Self. cfg = cfgDef _ setitem _ (self, key, value): self. cfg [key] = valuedef _ getitem _ (self, key): r
There are 10 turtles and 1 fish in a pond.1 classTurtle:2 def __init__ (self,x): # Describes the number of objects at the time of the Life object. (or an object. Quantity is just one property of the object.)3self.num=x4 5 classFish:6 def __init__ (self,x):7self.num=x8 9 classPool:Ten def __init__ (self,x,y): Oneself.turtle=Turtle (x) #在该对象中定义 turtle attribute, which is an instantiation of the Turtle object ASelf.fish=Fish (y) - def print_num (self): -Print'There's a turtle%d in the pond.'% Self.
to be added dynamically on student instances. __slots__= ('name',' Age')#Define a property name that allows binding by using a tuple classgraduatestudent (Student):Passif __name__=='__main__': S=Student () s.name='lky'S.age= 25#S.score = Print(S.name, S.age)#__slots__-defined properties work only on the current class instance and do not work on inherited subclasses, unless __SLOTS__ is also defined in the subclass, so that the subclass instance allows the defined property to be its ow
Python inherits that subclasses can override various methods of the parent class, including the __init__ method.If you want to overwrite the __init__ method of the parent class, and you want to refer to the __init__ method of the parent class in the overridden method, such as adding some properties to the __init__ method of the parent class or something else.You need to display a method that references the parent class, otherwise the parent class's me
Code: Class A (): def Add (self,a,b): return A+bclass B (A): Def sub (self,a,b): Return A-bprint (b (). Add (4,5) )Results:Python 3.5.2 (V3.5.2:4DEF2A2901A5, June, 22:18:55) [MSC v.1900-bit (AMD64)] on Win32type "copyright", "credits" or "license ()" For more information.>>> ======================= restart:d:/selenium/test/5.py ============== =========9>>>Analysis: Method exists in parent Class A: Add ()Subclass B Inherits parent Class A through B (a)You can therefore use the Add method in a par
Objects are composed of methods and propertiesThe characteristics of an object are called propertiesThe behavior of an object is called a methodNamed objectsclass Bian3: def aaa (Self,num): self.num=num def bbb (self): Print( " the number entered is%d " % self.num)>>> a=bian3 ()>>> A.AAA (2)>>> a.bbb ()The number entered is 2.Here are two more examples:classBian:def __init__(self,name): Self.name=namedefsss (self):Print('My name is%s, hello.'%self.name) #注意__init__ () metho
access the property, this method truncates your access behavior and takes precedence over the code in this method, which should be the highest priority in the property lookup order.Property Lookup Order:Instance of the Getattribute--> instance object Dictionary--the class dictionary where the instance is located--the parent class of the instance (MRO order) dictionary--getattr--> error of the instance's classclass People: a = 200class Student(People): a = 100 def __init__(self, a):
I have defined a Class A (object) in file a.py, and now I want to create an object of a in a function in class B in b.py, what do I need to do?I added import a.py to the head of B.Then use the statement obj = A () to always errorhttp://hi.baidu.com/kxw102/item/bbc7db11a863e00ab88a1a0cThe correct method should be: Froma import aLet's take a look at the specific principles:Python is located in the namespace.Import A is the introduction of a module, the name is a; You can import a as B: This introd
Inheriting the most interesting application is to add functionality to the built-in class, in the previous contact class, we add the contact to all the contacts list, if you want to search by name, then you can add a method to search in the touch class, but this method actually belongs to the list itself, We can use inheritance to do this:classcontactlist (list):defSearch (self, name):" "Return All contacts this contain the search value in their name." "matching_contacts= [] forContactin
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.