Python 3 Grammar (eight) class Class__python

Source: Internet
Author: User
Tags in python
There are only new classes in Python 3, no legacy classes, no designations to display, classes you define are new classes

If you don't know the difference between the new class and the old one, then you don't have to know.


Defined:

>>> class Nothing:
	#定义方法和属性
	pass

>>>


The class inside defines the method with Def, which is not called a function, because the first argument of each method is self, but we do not have to provide it when called, and the program automatically binds the first parameter to the instance that belongs to it.

>>> class Hello:
	def greet (self,name):
		print ("Hello," +name)

		
>>> me = Hello () #要加 () Otherwise, Not an instance
>>> me.greet (' Cheng ') #只需第一个参数
Hello,cheng


The methods and features in Python are public by default, and if you want to be private, add a double underline to the name of the method and feature.

>>> class Some:
	name = "Jane"

	
>>> she = Some ()
>>> she.name #这里可以访问
' Jane ' C4/>>>> class Some:
	 __name = "Jane"

	
>>> she = Some ()
>>> she.name  #这里不可以
Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    she.name
attributeerror: ' Some ' object has no attribute ' n Ame '
>>> she._some__name #通过 _ Class name __ method or feature name, we can access it
' Jane '
>>> class C:
	def __ Test (self):
		print (' in C ... ') def call
	(self):
		self.__test () #类内访问私有方法和特性

		
>>> C = C ()
>>> C.call () in
c ...

So, you can't completely limit the methods and features that other people can't access to your class, so Python does not implement full encapsulation


Inherited:
Writing other class names in parentheses after the class statement means inheriting from a class
Class name (base class name)
Statement block

>>> class A:
	def PrintA (self):
		print ("in A ...")

		
>>> class B (a):
	def printb (self):
		print (' in B.. ')

		
>>> issubclass (a,b) #A不是B的子类
False
>>> issubclass (b,a) #B是A的子类
True
>>> b.__bases__  #B的基类
(<class ' __main__. A ', '
>>> b = B ()
>>> isinstance (b,b)  #询问b是否是B的实例
True
>>> B.printa () #访问A中的方法 in
A ...

Multiple inheritance:
The method of multiple inheritance is easy, just write together a few class names.


Class name (base class Name 1, base class Name 2, base class name 3)
Statement block

A method with the same name in a subclass overrides the method of the base class, and the invocation of the method is related to the order in which the method is found in the parent class from left to right when it is not located in the child class.

Look at the following example:

>>> class A:
	def Test (self):
		print ("in A ...")

		
>>> class B (a):
	def test (self)
		: Print (' in B ... ')

		
>>> class C (A):
	def Test (self):
		print (' in C ... ')

		
>>> class D (b,c):
	def test (self):
		print (' in D ... ')

		
>>> d = d ()
>>> d.test () #如果子类拥有该方法, which calls the method directly In D ...
>>> class D (b,c): #重定义类D
	pass

>>> d = d ()
>>> d.test () #B先继承, the method is first found in B, Call B's method in B ...
>>> class D (c,b): #再次重定义, changed the inheritance order
	pass

>>> d = d ()
>>> d.test () #这次调用了C的方法 In C ...
>>> 

Of course, if D, B, C does not have this method, and a has, then naturally is the method of calling a


>>> hasattr (d, ' Test ') #对象d是否有test方法
True
>>> hasattr (d, ' next ') #对象d是否有next方法
False
>>> hasattr (d.test, ' __call__ ') #询问d的test方法是否可调用
True


"Constructor" __init () of the Python class

When the class is instantiated, an empty class instance is created, and a special method is initialized in the definition of a generic Python class, and this method is __init__ (), and the __init__ () method is immediately invoked by an instance of the class when the instantiation method of the class is invoked. So, __init__ () is not a constructor, but a common method.

>>> class A:
	count = 0;
	def __init__ (self):
		A.count + 1  #每次调用该方法 count self-add 1
	def output (self):
		print (self.count)

		
>> > a1 = A () 
>>> a1.output ()
1
>>> a2 = A () 
>>> a2.output ()
2
>>> class A:
	def __init__ (self,name):
		self.name = name

		
>>> a = A (' Jane ')


Python also has a method like "destructor" __del__, but it is not recommended, Python's memory management is counted by reference, but the reference count is 0 o'clock to destroy the object, but you can hardly determine when Python will call the Del method, So the best way to avoid a baffling mistake is not to use it, write all the things you want Del to do in an unsolicited way, and then manage it yourself

Again, Python's class and instance properties

Class attributes are variables that belong to a class. Just like the static member variable of a class in C + +, you simply define the attribute in the scope of all methods, that is, the class attribute, but usually immediately after the class name, the class attribute is common to all instances, and you can invoke the Class property by using the class name. property

>>> class A:
	count = 0 #这就是类属性
	def __init__ (self):
		a.count = 1  #每次调用该方法 count self-add 1
	def OUTP UT (self):
		print (Self.count)

>>> a1 = A ()
>>> a1.output ()
1
>>> A.count = 0
>>> a.count
0
>>> a1.output ()
0


Instance properties are properties that belong to the instance, you can add new instance properties to any method, even outside the class, and Python creates the property and assigns it when the instance property is first used

>>> class A:
	def __init__ (self):
		self.num = 1  #添加实例属性num
	def again (self,name):
		Self.name = name #添加实例属性name

		
>>> a1 = A ()
>>> a1.num
1
>>> a1.name #这时实例 A1 has no instance property name
Traceback (most recent call last):
  File ' <pyshell#38> ', line 1, in <module>
    a 1.name #这时实例 A1 has no instance attribute name
attributeerror: ' A ' object has no attribute ' name '
>>> a1.again (' Jane ') C28/>>>> a1.name #现在有了 ...
' Jane '
>>> a1.call = ' 123456 ' #添加a1的实例属性 call
>>> a1.call
' 123456 '


Keep looking at the following example:

>>> class A:
	count = 0
	def __init__ (self):
		A.count + + 1
	def output (self):
		print ( Self.count)

		
>>> a1 = A ()
>>> a2 = A ()
>>> a3 = A ()
>>> A.count # A's class properties Count is 3
3
>>> a.count = 2 #更改A的类属性为2
>>> a1.count,a2.count, A3.count, A.count # The count for all instances of a also changes
(2, 2, 2, 2)
>>> a1.count = 5 #通过A的一个实例a1更改count
>>> A1.count, A2.count, A3.count, A.count #只有a1的count发生改变
(5, 2, 2, 2)
>>> a.count = 4 #再次更改A的类属性为4
>>& Gt A1.count, A2.count, A3.count, A.count  #这时a1的count还是保持为5
(5, 4, 4, 4)  

As we can see from the above example, class attributes are common to all instances and classes, class properties can be changed by the class name. class properties, and the class properties of all instances change, but the class property is changed by the instance name. Class property, which changes to the instance property without affecting the class properties of the other instances. Class name. Class property to change the class property, nor does it affect the property of the instance because it becomes an instance property. (OK, I admit a little dizzy O (╯-╰) o)






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.