Initial python (11) __ Class

Source: Internet
Author: User

Python class

Python class is defined as a category that has the same properties and methods.

For example, put Automotive this noun is a class that we can call a car class.
Car properties can be wheels, steering wheel and so on, can be used to carry passengers, girls, etc.
Classes can be instantiated, instantiated objects can have the properties and methods of this class, for example, Lamborghini is an instantiation of the car, so Lamborghini has the properties and methods of the car, there are wheels, such as the steering wheel and other properties of this class, but also all the methods of this class can be used to pick up girls, passengers.

we are python A class that is customized in order to have the same properties and methods as the instantiated object, so that it is not necessary to write a statement every time to achieve the same function.

in the python , a feature of an object is also known as a property ( attribute ). The behavior it has is also called the method.
Conclusion: The object = Properties + Method

in the python , the objects that have the same properties and methods are grouped into a single class ( class )

Private properties of the class:
__private_attrs Two underscore, declaring that the property is private and cannot be used outside of the class or accessed directly
when used in methods inside a class self.__private_attrs

Methods of the class

inside the class, use thedefkeyword can define a method for a class, unlike a generic function definition, a class method must contain a parameter Self,and for the first parameter, SelfThe function is that once the method is instantiated, a reference such asA.speak () speak self is equivalent to a This example is actually telling the argument which instance was referenced. Equivalent to Speak (A) =a.speak ()

Class definition

#class definitionclasspeople:#Defining basic PropertiesName ="' Age=0#define private properties, private properties cannot be accessed directly outside the class__weight=0#Defining construction Methodsdef __init__(self,n,a,w): Self.name=Nself.age=aself.__weight=WdefSpeak (self):Print("%s is speaking:i am%d years old"%(self.name,self.age))>>>jack = People ('Tom', 10,30)#Create a P instance>>> Jack.speak ()#referencing the Speak methodhello!>>> jack.height=120#Add Height Property>>>Jack.height120

Initializing objects

When you create a class, you can define a specific method named _ _init__ () , __init__ () method passes parameters so that when you create an object, you can set the property to the value you want __init__ ()

Class and class inheritance

1. Single Inheritance

 Class < category name >(parent class name)< statement >
eg. class  = 10

2. Multiple Inheritance of classes

class Class Name (parent Class 1, parent Class 2,...., parent class N)< statement 1>

Note the order of the parent class in parentheses, if the same method name is in the parent class and is not specified when the subclass is used, Python searches from left to right

If the method is not found in the subclass, look from left to right to see if the method is included in the parent class

classSchoolmember:"""represents any School Member"""    def __init__(Self, name,age):#__init__ Analysis of __init__ see belowSelf.name =name Self.age= AgePrint 'initailized schoolmember:%s'%(Self.name)defTell (self):" "Tell my details." "        Print 'Name:%s,age:%s'%(self.name,self.age),classTeacher (schoolmember):" "represents a Teacher." "    def __init__(self,name,age,salary): Schoolmember.__init__(Self,name,age)#For this sentence, see sub-class constructorsSelf.salary =SalaryPrint 'initailized Teacher:%s'%Self.namedefTell (self): Schoolmember.tell (self)Print 'Salary:%d'%self.salaryclassStudent (schoolmember):" "represents a student." "    def __init__(self, name, age, marks): Schoolmember.__init__(self, name, age) Self.marks=MarksPrint '(Initialized Student:%s)'%Self.namedefTell (self): Schoolmember.tell (self)Print 'Marks: "%d"'%Self.markst= Teacher ('Mrs. Shrividya', 40, 30000) s= Student ('Swaroop', 22, 75)Print #prints a blank line Members=[T, S] forMemberinchMembers:member.tell ()#works for both Teachers and StudentsThe results of the operation are as follows: initailized Schoolmember:mrs shrividyainitailized Teacher:mrs. shrividyainitailized SchoolMember: Swaroop (Initialized student:swaroop) Name:mrs. Shrividya,age:salary:30000Name:swaroop,age:Marks:" the" 

sub-class constructor note: If necessary, each subclass is best to define its own constructor, otherwise the constructor of the base class is called _ _init__ method, the constructor of the base class is automatically called when the subclass is run Span style= "Font-family:times New Roman;" >) schoolmember.__init__ (self,name,age) Set the name and age. Our subclasses also set another instance property in a few lines after the constructor: salary salary

classP (object):def __init__(self):Print "calling P ' s constructor"classC (P):def __init__(self):Print "calling C ' s constructor">>> C =C () calling C'S Constructor#If you want to call the base class's __init__ (), you need to make it clear that use an instance of a subclass to tune # with the base class (unbound) method. When Class C is updated accordingly, the following expected execution results appear:classC (P):def __init__(self): P.__init__(self)Print "calling C ' s constructor">>> C =C () calling P'S ConstructorCalling C'S Constructor

_ _init__ () method first calls the base class's __init__ () method. This is fairly common (not mandatory) practice to set the initialization base class, and then you can execute the settings inside the subclass. The reason why this rule makes sense is You want the object of the inherited class to be well initialized or ready to work before the subclass constructor is run, because it subclass You may need or set an inheritance property.

about the __init__:

classA (object):def __init__(self,name): Self.name=namedefGetName (self):return 'A'+Self.name#when executing:A=a ('Hello')#equivalent to:A=object.__new__(a) a.__init__A'Hello')#that is, the __init__ function is to initialize the object after it has been instantiated

Initial python (11) __ Class

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.