程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python | class foundation

編輯:Python

1、 Class definition

The syntax is as follows :

class ClassName:<statement-1>

……

<statement-N>

After class instantiation , You can use its properties , actually , After creating a class , Can pass The class name accesses its properties .

2、 Class object

Class objects support two operations : Property references and instantiations . Property references use and Python All attribute references in Use the same standard syntax :obj.name. After the class object is created , All names in the class namespace Are valid attribute names .

Attributes are variables defined by a class , A method is a function defined by a class

class MyClass:
   """ A simple class instance """
   i = 12345
   def f(self):
       return 'hello world'
​
# Instantiate the class
x = MyClass()
# Access class properties and methods
print("MyClass Attributes of a class i by :", x.i)
print("MyClass Class method f Output is :", x.f())

The above creates a new class instance and assigns the object to a local variable x,x Empty object . The output of the above program is : MyClass Attributes of a class i by : 12345 MyClass Class method f Output is : hello world

3、__init__()

Class has a name __init__() Special method ( Construction method ), This method is called automatically when the class is instantiated , Like this :

def_init_(self):
   self.data = []

Class definition __init__() Method , Class instantiation will Automatically call init() Method . Instantiate the class as follows MyClass, Corresponding __init__() Method will be called :

x = MyClass()

Of course , init() Method can have parameters , Parameters through init() Passed to the instantiation operation of the class . for example :

class Complex:
   def __init__(self, realpart, imagpart):
       self.r = realpart
       self.i = imagpart
​
x = Complex(3.0, -4.5)
print(x.r, x.i)   # Output results :3.0 -4.5

self Represents an instance of a class , Not class There is only one special difference between a class method and a normal function —— They must have an additional first parameter name , By convention it's The name is self

class Test:
   def prt(self):
       print(self)
       print(self.__class__)
​
​
t = Test()
t.prt()

<main.Test object at 0x000001F1C3674F40> <class 'main.Test'>

It is obvious from the execution results ,self Represents an instance of a class , Represents the address of the current object , and self.class Point to class . self No python keyword , We'll replace him with Huawei It can also be executed normally

4、 Class method

Inside the class , Use def Keyword to define a method , Different from general function definition , Class method must contain parameters self, And For the first parameter ,self Represents an instance of a class .

# Class definition
class people:
   # Define basic attributes
   name = ''
   age = 0
   # Define private properties , Private properties cannot be accessed directly outside the class
   __weight = 0
​
   # Define construction method
   def __init__(self, n, a, w):
       self.name = n
       self.age = a
       self.__weight = w
​
   def speak(self):
       print("%s say : I %d year ." % (self.name, self.age))
​
​
# Instantiate the class
p = people('Huawei', 10, 30)
p.speak()

Huawei say : I 10 year .

5、 Inherit

Python Class inheritance is also supported , If a language does not support inheritance , Classes have no meaning . Definition of derived class As shown below :

class DerivedClassName(BaseClassName1):
<statement-1>
.
.
.
<statement-N>

Note the order of base classes in parentheses , If there is the same method name in the base class , When subclass is used, it does not specify , python Search from left to right When the method is not found in the subclass , Find whether the base class contains methods from left to right

BaseClassName( The base class name in the example ) Must be in the same scope as the derived class definition . Except class , You can also use expressions , Base class definition This is useful in another module :

class DerivedClassName(modname.BaseClassName):
# Class definition
class people:
   # Define basic attributes
   name = ''
   age = 0
   # Define private properties , Private properties cannot be accessed directly outside the class
   __weight = 0
​
   # Define construction method
   def __init__(self, n, a, w):
       self.name = n
       self.age = a
       self.__weight = w
​
   def speak(self):
       print("%s say : I %d year ." % (self.name, self.age))
​
​
# Single inheritance example
class student(people):
   grade = ''
​
   def __init__(self, n, a, w, g):
       # Call the constructor of the parent class
       people.__init__(self, n, a, w)
       self.grade = g
​
   # Override method of parent class
   def speak(self):
       print("%s say : I %d Year old , I'm reading %d grade " % (self.name, self.age, self.grade))
​
​
s = student('Huawei', 10, 60, 3)
s.speak()

Huawei say : I 10 Year old , I'm reading 3 grade

6、 Multiple inheritance

Form the following :

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>

Note the order of the parent classes in parentheses , If the parent class has the same method name , When subclass is used, it does not specify ,python Search from left to right Cable When the method is not found in the subclass , From left to right, find whether the parent class contains methods

# Class definition
class people:
   # Define basic attributes
   name = ''
   age = 0
   # Define private properties , Private properties cannot be accessed directly outside the class
   __weight = 0
​
   # Define construction method
   def __init__(self, n, a, w):
       self.name = n
       self.age = a
       self.__weight = w
​
   def speak(self):
       print("%s say : I %d year ." % (self.name, self.age))
​
​
# Single inheritance example
class student(people):
   grade = ''
​
   def __init__(self, n, a, w, g):
       # Call the constructor of the parent class
       people.__init__(self, n, a, w)
       self.grade = g
​
   # Override method of parent class
   def speak(self):
       print("%s say : I %d Year old , I'm reading %d grade " % (self.name, self.age, self.grade))
​
​
# Another class , Preparation for multiple inheritance
class speaker():
   topic = ''
   name = ''
​
   def __init__(self, n, t):
       self.name = n
       self.topic = t
​
   def speak(self):
       print(" My name is %s, I'm a speaker , The theme of my speech is %s" % (self.name, self.topic))
​
​
# multiple inheritance
class sample(speaker, student):
   a = ''
​
   def __init__(self, n, a, w, g, t):
       student.__init__(self, n, a, w, g)
       speaker.__init__(self, n, t)
​
​
test = sample("Huawei", 25, 80, 4, "Python")
test.speak()  # Same method name , By default, the method of the parent class in brackets is called 

My name is Huawei, I'm a speaker , The theme of my speech is Python

7、 Method rewriting

class Parent:  # Define parent class
   def myMethod(self):
       print(' Call the superclass method ')
​
​
class Child(Parent):  # Defining subclasses
   def myMethod(self):
       print(' Call subclass method ')
​
​
c = Child()  # Subclass instance
c.myMethod()  # Subclass call override method
super(Child, c).myMethod()  # Call the overridden method of the parent class with the child class object ,super() Function is used to call the parent class ( Superclass ) One way .

Call subclass method Call the superclass method

8、 Class ( private ) Properties and methods

Private properties of class

private_attrs: Start with two underscores , Declare the property private , Can't be used outside of the class or accessed directly . Inside the class When used in self.private_attrs

Class method Inside the class , Use def Keyword to define a method , Different from general function definition , Class method must contain parameters self, And first Parameters ,self Represents an instance of a class . self The name of is not meant to be dead , You can also use this, But it's better to use it as agreed self.

Private method of class :

Example 1 :

class JustCounter:
   __secretCount = 0  # Private variables
   publicCount = 0  # Open variables
​
   def count(self):
       self.__secretCount += 1
       self.publicCount += 1
       print(self.__secretCount)
​
​
counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter.__secretCount)  # Report errors , Instance cannot access private variables 

1 2 2 Traceback (most recent call last): File "E:\ Big data competition \mystudy\ex_821.py", line 15, in <module> print(counter.secretCount) # Report errors , Instance cannot access private variables AttributeError: 'JustCounter' object has no attribute 'secretCount'

Example 2:

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):  # Private method
       print(' This is the private method ')
​
   def foo(self):  # Public methods
       print(' It's the public way ')
       self.__foo()
​
​
x = Site(' Extreme value College ', 'http://edu.mathor.com/')
x.who()  # Normal output
x.foo()  # Normal output
x.__foo()  # Report errors 

Traceback (most recent call last): File "E:\ Big data competition \mystudy\ex_822.py", line 21, in <module> x.foo() # Report errors AttributeError: 'Site' object has no attribute 'foo' name : Extreme value College url : Extreme vocational education - Let everyone find a satisfactory job It's the public way This is the private method

9、 Class

10、 operator overloading

class Vector:
   def __init__(self, a, b):
       self.a = a
       self.b = b
​
   def __str__(self):
       return 'Vector (%d, %d)' % (self.a, self.b)
​
   def __add__(self, other):
       return Vector(self.a + other.a, self.b + other.b)
​
​
v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)

Vector (7, 8)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved