Home > Article > Backend Development > How to use classes and methods in Python
Class (Class): Used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes.
Method: Function defined in the class.
Constructor method of class __init__(): The class has a special method (constructor) named init(), which is used when the class is instantiated will be called automatically.
Instance variable: In the declaration of a class, attributes are represented by variables. This type of variable is called an instance variable. An instance variable is a variable using self Modified variables.
Instantiation: Create an instance of a class, a specific object of the class.
Inheritance: That is, a derived class inherits the fields and methods of the base class. Inheritance also allows an object of a derived class to be treated as a base class object. For example, there is such a design: an object of type Dog is derived from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).
Python’s class (class) is equivalent to a family composed of multiple functions. If there is a person named Myclass in this big family f, if this f has the function of printing the weather, then if one day I need this f to print today's weather, then I must call his full name MyClass.f before he can print it to me, that is, after calling his Time needs to bring his family name his name.
Attributes: Attributes are variables in this class. If the variable is an item, then the different attributes are different items in this big family
Method: The method is the function in this class. If functions are people, then different methods are different people in this big family.
MyClass instance:
#Myclass家族,但是这个家族只有一个人f class MyClass: """一个简单的类实例""" i = 12345 def f(self): return 'hello world' # 实例化类 x = MyClass() # 访问类的属性和方法 print("MyClass 类的属性 i 为:", x.i) #家族x + 物品名i print("MyClass 类的方法 f 输出为:", x.f()) #家族x + 人名f
Output result:
__init__()
If init() is also a person, but he is the liaison between the family and the outside world, when people from the outside want to call people from their own family, You must tell him first, so as long as a family member is called, init() will be executed first, and then he will tell the called person to execute the called one.
init() example:
class Complex: def __init__(self, realpart, imagpart): #必须要有一个self参数, self.r = realpart self.i = imagpart x = Complex(3.0, -4.5) print(x.r, x.i) # 输出结果:3.0 -4.5
Output result:
##3. Parameters of methods in a class
self: There is only one special difference between class methods and ordinary functions - there must be an additional first parameter name. By convention it The name is self.
Instance of class: It is to apply the class in the instance scenario. For example, there is a function in the class f. If this f has print at a certain time The ability of weather conditions, then if I need this f to print the weather at 12 o'clock today, then the action of letting him print the weather at 12 o'clock today is the instantiation of the class, making the capabilities of the functions in the class real. Actions.
Instantiated instance:
#类定义 class people: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 #定义构造方法 def __init__(self,n,a): self.name = n self.age = a def speak(self): print("%s 说: 我 %d 岁。" %(self.name,self.age)) # 实例化类 p = people('Python',10,30) p.speak()
Output result:
4. Inheritance If there are two families, and one family A begins to decline, and another emerging family B wants to inherit the materials and servants of family A, then it can be achieved through the following methods Inheritance, here, family A is the parent class, and family B is the child class. In terms of usage, if family B can use the items and servants of family A at will.
class [子类]([父类]):
BaseClassName (the base class name in the example) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is useful when the base class is defined in another module.
Multiple inheritance, that is, you can inherit multiple parent classes. The inheritance method is the same as the single inheritance method, and the method is as follows:
class [子类]([父类]1, [父类]2, [父类]3):
Inheritance example:
#类定义 class people: #定义基本属性 name = '' age = 0 #定义私有属性,私有属性在类外部无法直接进行访问 __weight = 0 #定义构造方法 def __init__(self,n,a,w): self.name = n self.age = a self.__weight = w def speak(self): print("%s 说: 我 %d 岁。" %(self.name,self.age)) #单继承示例 class student(people): #student为子类,people为父类 grade = '' def __init__(self,n,a,w,g): #调用父类的构函 people.__init__(self,n,a,w) self.grade = g #覆写父类的方法 def speak(self): print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade)) s = student('ken',10,60,3) s.speak()
Running result:
如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法。即如果B家族继承了A家族,但是B家族有个佣人只会扫地,于是A家族给这个人洗脑,让他啥都不会,然后再教这个佣人洗碗、擦桌子的技能,那么这个佣人就只会洗碗和擦桌子了。
super()函数是用于调用父类(超类)的一个方法。
方法重写实例:
class Parent: # 定义父类 def myMethod(self): print('调用父类方法') class Child(Parent): # 定义子类 def myMethod(self): print('调用子类方法') c = Child() # 子类实例 c.myMethod() # 子类调用重写方法 super(Child,c).myMethod() #用子类对象调用父类已被覆盖的方法
输出结果:
_private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。
私有属性实例:
class JustCounter: __secretCount = 0 # 私有变量 publicCount = 0 # 公开变量 def count(self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount) counter = JustCounter() counter.count() counter.count() print(counter.publicCount) print(counter.__secretCount) # 报错,实例不能访问私有变量
输出结果:
__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。
私有方法实例:
class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # 私有方法 print('这是私有方法') def foo(self): # 公共方法 print('这是公共方法') self.__foo() x = Site('Python', 'www.irvingao.com') x.who() # 正常输出 x.foo() # 正常输出 x.__foo() # 报错
输出结果:
The above is the detailed content of How to use classes and methods in Python. For more information, please follow other related articles on the PHP Chinese website!