Attributes are divided into instance properties and class properties
Methods are divided into ordinary instance methods, class methods, static methods
Both static and class methods of Python can be accessed by a class or instance, and the difference is obvious:
1) Static methods do not need to pass in the self parameter, the class method needs to pass in the CLS parameter representing this class;
2) from the 1th, the static method is unable to access the instance property, and the class method also cannot access the instance variable, but can access the Class property;
3) Static methods are a bit like function ToolPak, and class methods are closer to static methods similar to those in Java object-oriented concepts.
#!/usr/bin/python#-*-coding:utf-8-*-classTest (Object): Val1= "I am a class attribute Val1" def __init__( Self): Self. Name= "I am an instance attribute Self.name" Print "-"* - defTest1 ( Self):Print "Tes1" Print "I am an Ordinary instance method" Print "Can definitely invoke class properties", Test.val1,Print "I was called by Test1." Print "can also invoke instance properties", Self. Name,Print "I was called by Test1." Print Self Print "-"* - @classmethod defTest2 (CLS):#必须传入cls, by distinction and by other means Print "Test2" Print "I am the class method" Print "I can invoke class properties, but I can't invoke instance properties" PrintTest.val1,Print "I was called by Test2." PrintCls#print Self.name cannot invoke instance properties, otherwise it will error, same as static method Print "-"* - @staticmethod defTest3 ():#静态方法可以不用带参数 Print "Test3" Print "I am a static method" Print "Can invoke class properties, but cannot invoke instance properties" PrintTest.val1,Print "I was called by Test3." Print "-"* -if __name__ == "__main__": t=Test () T.test1 () T.test2 () T.test3 ()
Python: Class Properties, instance properties, private properties and static methods, class methods, instance methods