In this article let's look at the knowledge about classes, some friends may have just come into contact with the Python programming language, for
Python class PropertiesThis is not a special understanding, but it's okay. The next article will come to take you to learn
Python Class Property methodsThis aspect of knowledge, well, nonsense not much to say we begin to enter the article to learn it.
Private properties of the class
__private_attrs: Two underscores begin with, declaring that the property is private and cannot be used outside of the class or accessed directly. Used in methods inside the class or accessed directly. Self.__private_attrs when used in methods inside a class.
Methods of the class
Inside a class, you can define a method for a class by using the DEF keyword, which differs from the general function definition in that the class method must contain the parameter self, which is the first argument.
Private methods of the class
__private_method: Two underscores, declares that the method is a private method, and cannot be called outside of a class. Calls Self.__private_methods inside the class.
Examples are as follows:
#!/usr/bin/python#-*-Coding:utf-8-*-class Justcounter: __secretcount = 0 # private variable publiccount = 0 # public variable Volume def count (self): Self.__secretcount + = 1 self.publiccount + = 1 print Self.__secretcount counter = Justcounter () Counter.count () Counter.count () print counter.publiccountprint counter.__secretcount # Error, Instance cannot access private variables
Python includes the class name by changing its name:
Traceback (most recent): File "test.py", line <module> print Counter.__secretcount # error, instance cannot access private variable Attributeerror:justcounter instance has no attribute ' __secretcount '
Python does not allow instantiated classes to access private data, but you can use Object._classname__attrname (object name. _ Class Name __ Private property name) to access the property, referring to the following example:
#!/usr/bin/python#-*-coding:utf-8-*-class runoob: __site = "www.runoob.com" Runoob = Runoob () print Runoob. _runoob__site
After executing the example above, the output is as follows:
Www.runoob.com