Home > Backend Development > Python Tutorial > What are the basic methods of using Python classes?

What are the basic methods of using Python classes?

WBOY
Release: 2023-05-17 23:58:04
forward
5378 people have browsed it

1. Object-oriented

Class (class): It is a collection of objects used to describe the same properties and methods.

Class variables: Class variables are public throughout the instantiated object. Generally defined in the class and outside the function body.

Method: Function in the class

Data members: Class variables or instance variables are used to process data related to the class and its instance objects.

Method rewriting: If the method inherited from the parent class cannot meet the needs of the subclass, it can be rewritten. This process is called method override, also known as method rewriting.

Local variables: Variables defined in methods only act on the class of the current instance.

Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self.

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. Just like we define a fruit class, and then define a derived class apple, which has some attributes and methods of the fruit class, and also has some unique attributes and methods of its own, which are similar to the fruit class. It is an 'is-a' relationship.

Instantiation: A specific object of the class. The class image is like a template. Only after we instantiate it into an object can we perform corresponding operations on it.

Object: Data structure instance defined through a class. Objects include two data members (class variables and instance variables) and methods.


2. Class definition

Define a class:

class ClassName:....    ....    ....
Copy after login

It is recommended that the class name be named in camel case, or all capital letters


3. Use class object methods

Class objects support two operations: attribute reference and instantiation

Attribute reference: and in python The other syntax is the same. The attributes with __ in obj.name

are private attributes of the class. Private attributes cannot be directly accessed outside the class. The output result like __name.

class Fruit:#这是类的一个基本属性self.number = 100def get_number(self):                a = self.number + 100return a

f = Fruit()print('We have {0} fruits'.format(f.number))print('We have {0} fruits'.format(f.get_number()))
Copy after login

is:

We have 100 fruitsWe have 200 fruits
Copy after login

4. Construction method

There is a special method named __init__() in the python class, which is called the construction method. This method is executed in the class It will be called automatically during instantiation (can be used for class attribute initialization, etc.), similar to the constructor of a class in C.

def __init__(self):self.data = []
Copy after login

The class defines the __init__() method, and the instantiation operation of the class will automatically call the __init__() method.

class Fruit:def __init__(self):                print('你已经实例化了一个对象')
f = Fruit()
Copy after login

Output results

你已经实例化了一个对象
Copy after login

The init_() method can have parameters, and the parameters are passed to the instantiation operation of the class through init().

class Complex:def __init__(self,real,image):self.r = realself.i = imagedef get_complex(self):                print('complex real is %.2f , image is %.2f'%(self.r,self.i))
a = Complex(3.5,-3)a.get_complex()
Copy after login

The output is as follows:

complex real is 3.50 , image is -3.00
Copy after login

self represents an instance of a class, not a class. There is only one special difference between class methods and ordinary functions - they must have an additional first parameter name, which by convention is self. But self is not a keyword in Python.

I wonder if it can be understood this way. Self represents the address of the object after you instantiate an object according to a class. Much like this pointer in C class

class Test:def prt(self):        print(self)        print(self.__class__)
t = Test()t.prt()
Copy after login

Output:

<__main__.Test object at 0x0000025EC6D45608><class &#39;__main__.Test&#39;>
Copy after login

5. Class method

Inside the class, use def Keyword to define a method. Unlike general function definitions, class methods must contain the parameter self, which is the first parameter. If you do not need to pass parameters by self, you need to add @staticmethod in front of the function to indicate the static method

class Complex:def __init__(self, real=None, image=None):self.r = realself.i = image
def get_complex(self):        print('complex real is %.2f , image is %.2f' % (self.r, self.i))
    @staticmethoddef test(a, b):        print('complex real is %.2f , image is %.2f' % (a, b))

a = Complex(3.5, -3)a.get_complex()
b = Complex()b.test(3, -2)
Copy after login

Output results

complex real is 3.50 , image is -3.00complex real is 3.00 , image is -3.00
Copy after login

6. Inheritance

Python also supports class inheritance, the format is as follows:

class Derivedclassname(Baseclassname):    ...    ...
Copy after login

Baseclassname (base class name) must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is very useful when the base class is defined in another module:

class Fruit:    def __init__(self,sweet):        self.sweetness = sweet    def describe(self):        print('Our fruit has a sweetness of %.2f'%self.sweetness)
class Apple(Fruit):#单继承,继承fruit类    def __init__(self,sweet,color):        self.color = color        Fruit.__init__(self,sweet)    def describe(self):#改写基类fruit的方法        print('Our apple has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness,self.color))

apple = Apple(62.2,'red')apple.describe()
Copy after login

Output:

Our apple has a sweetness of 62.20%,and color is red
Copy after login

Multiple inheritance

Python can also Inheriting multiple base classes:

class Derivedclassname(basename1,basename2,...):    ...    ...    ...
Copy after login

You need to pay attention to the order of the parent class in the parentheses. If there is the same method name in the parent class, but it is not specified when using the subclass, python searches from left to right, that is When the method is not found in the subclass, search from left to right to see if the method is included in the parent class.

class Fruit:def __init__(self, sweet):        self.sweetness = sweetdef describe(self):        print('Our fruit has a sweetness of %.2f' % self.sweetness)

class Food:def __init__(self, uprice, num):        self.unit_price = uprice        self.number = num        self.total_price = num * upricedef cost(self):        print('You need to pay {0:.3} yuan, thank you'.format(self.total_price))

class Apple(Fruit, Food):def __init__(self, sweet, color, uprice, num):        self.color = color        Fruit.__init__(self, sweet)        Food.__init__(self, uprice, num)def describe(self):        print('Our fruit has a sweetness of {0:.2f}%,and color is {1}'.format(self.sweetness, self.color))
Copy after login
rrree

Output:

Our fruit has a sweetness of 62.20%,and color is redYou need to pay 73.5 yuan, thank you
Copy after login

7、方法重写

如果父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法,如果想调用已经被覆盖的基类方法,可以用super(子类名,子类实例对象名).父类方法

class Parent_class:def Method(self):         print ('父类方法')

class Child_class(Parent_class): # 定义子类def Method(self):        print ('子类方法')

c = Child_class()                # 子类实例化c.Method()                  # 子类调用重写方法super(Child_class,c).Method()    #用子类对象调用父类已被覆盖的方法
Copy after login

子类继承父类构造函数

如果在子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法。

class A:def __init__(self, x, y):        self.x = x        self.y = y        print('pos is ({0},{1})'.format(self.x, self.y))
def xxx(self):        print('parent now')

class B(A):def xxx(self):        print('child now')

b = B(10, 3)b.xxx()
Copy after login

输出

pos is (10,3)child now
Copy after login

如果重写了__init__ 时,实例化子类,就不会调用父类已经定义的 __init__。

如果重写了__init__ 时,要继承父类的构造方法,可以使用 super 关键字super(子类,self).__init__(参数1,参数2,....),或者父类名称.__init__(self,参数1,参数2,...)


8、类的私有属性

两个下划线开头,声明该属性为私有,像__name不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__name。

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)  # 报错,实例不能访问私有变量
Copy after login
Traceback (most recent call last):File "test.py", line 16, in <module>    print (counter.__secretCount)  # 报错,实例不能访问私有变量AttributeError: 'JustCounter' object has no attribute '__secretCount'
Copy after login

两个下划线开头,声明该方法为私有方法,像__private_method,只能在类的内部调用 ,不能在类的外部调用。self.___private_method。

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('***', 'www.xxx.com')x.who() # 正常输出x.foo() # 正常输出x.__foo()  # 报错
Copy after login

输出:

'''name  :  ***url :  www.***.com这是公共方法这是私有方法Traceback (most recent call last):  File "F:\Python\Program\test.py", line 61, in <module>    x.__foo()      # 报错AttributeError: 'Site' object has no attribute '__foo''''
Copy after login

类的专有方法

__init__ : 构造函数,在生成对象时调用,类似C++构造函数

__del__: 析构函数,释放对象时使用,类似C++析构函数,常用在释放申请的内存空间

__repr__: 打印,转换。这个个函数就是在打印类的时候,控制类输出的字符串

class Name:def __init__(self, name):        self.name = name

print(Name('s'))
Copy after login
'''<__main__.Name object at 0x0000023744AFD248>'''
Copy after login
class Name:def __init__(self,name):        self.name = name
def __repr__(self): #控制了在打印类时候的输出          return 'Name({!r})'.format(self.name)

print(Name('s'))
'''Name('s')'''
Copy after login

__setitem__ : 每当属性被赋值的时候都会调用该方法,因此不能再该方法内赋值 self.name = value 会死循环

__getitem__: 当访问不存在的属性时会调用该方法

__len__: 获得长度,如果一个类表现得像一个list,要获取有多少个元素,就得用len() 函数。要让len()函数工作正常,类必须提供一个特殊方法__len__(),它返回元素的个数。

class CountList:def __init__(self, *args):        self.list = [x for x in args]        self.count = self.__len__()
def __len__(self):         return len(self.list)
def get_count(self):         return self.count

a = CountList(1, 2, 3, 4, 4, 5)print(a.get_count())print(len(a))
Copy after login

__cmp__: 比较运算

__call__: 函数调用

__add__: 加运算

__sub__: 减运算

class MyClass:
def __init__(self, height, weight):        self.height = height        self.weight = weight
# 两个对象的长相加,宽不变.返回一个新的类def __add__(self, others):        return MyClass(self.height + others.height, self.weight + others.weight)
# 两个对象的宽相减,长不变.返回一个新的类def __sub__(self, others):        return MyClass(self.height - others.height, self.weight - others.weight)
# 说一下自己的参数def intro(self):        print("高为", self.height, " 重为", self.weight)

def main():    a = MyClass(height=10, weight=5)    a.intro()
    b = MyClass(height=20, weight=10)    b.intro()
    c = b - a    c.intro()
    d = a + b    d.intro()

if __name__ == '__main__':    main()
Copy after login
'''高为 10  重为 5高为 20  重为 10高为 10  重为 5高为 30  重为 15'''
Copy after login

__mul__: 乘运算

__truediv__: 除运算

__mod__: 求余运算

__pow__: 乘方

同样的。类的专有方法也可以重写

The above is the detailed content of What are the basic methods of using Python classes?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template