Class Class
In Python, all data types are treated as objects, of course, can also be custom objects. Custom object data type is object-oriented class (Class) concept .
Define a simple class
Class definition syntax:
class nameoftheclass(parent_class):
statement1
statement2
statement3
In the class declaration you can write any Python statements, including the definition of the function (called in the class method):
>>> class MyClass(object):
... """A simple example class"""
... i = 12345
... def f(self):
... return 'hello world'
__init__ method
Instantiate the class to use the function symbols. As long as the class object is a non-parametric function returns a new instance of the class can.
x = MyClass()
More than create a new instance of the class and assigns this object to the local variable x
. The instantiation operation creates an empty object .
Many classes like to create objects for an initial state . Therefore a class may define a named __init__()
special method:
def __init__(self):
self.data = []
Class defines a __init__()
method, then the class instantiation operator will call the new class instance is created automatically __init__()
method. So in this example, you can create a new instance:
x = MyClass()
__init__()
The method can have arguments. In fact, the parameters __init__()
passed to the class instantiation operator. E.g:
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
Python Inheritance
When a class inherits from another class, it inherits all the features (e.g., variables and methods) of the parent class. This helps to reuse code.
First, create a named Person
class, and then create two derived classes Student
and Teacher
. When the two classes from Person
time to inherit the class, in addition to their classes would Person
all methods of the class will have its own new methods and purpose of the variable.
#!/usr/bin/env python3
class Person(object):
"""
返回具有给定名称的 Person 对象
"""
def __init__(self, name):
self.name = name
def get_details(self):
"""
返回包含人名的字符串
"""
return self.name
class Student(Person):
"""
返回 Student 对象,采用 name, branch, year 3 个参数
"""
def __init__(self, name, branch, year):
Person.__init__(self, name)
self.branch = branch
self.year = year
def get_details(self):
"""
返回包含学生具体信息的字符串
"""
return "{} studies {} and is in {} year.".format(self.name, self.branch, self.year)
class Teacher(Person):
"""
返回 Teacher 对象,采用字符串列表作为参数
"""
def __init__(self, name, papers):
Person.__init__(self, name)
self.papers = papers
def get_details(self):
return "{} teaches {}".format(self.name, ','.join(self.papers))
person1 = Person('Sachin')
student1 = Student('Kushal', 'CSE', 2005)
teacher1 = Teacher('Prashad', ['C', 'C++'])
print(person1.get_details())
print(student1.get_details())
print(teacher1.get_details())
Multiple Inheritance
A class can inherit from more than one class, with all the variables and methods of the parent class, the following syntax:
class MyClass(Parentclass1, Parentclass2,...):
def __init__(self):
Parentclass1.__init__(self)
Parentclass2.__init__(self)
...
...
Deleting objects
Use keywords del
to delete objects:
>>> s = "I love you"
>>> del s
>>> s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
Properties reading method
Do not use the property in Python (attributes) reading methods (getters and setters). Properties can be used directly:
>>> class Student(object):
... def __init__(self, name):
... self.name = name
...
>>> std = Student("Kushal Das")
>>> print(std.name)
Kushal Das
>>> std.name = "Python"
>>> print(std.name)
Python
@property decorator
To be more precise adjustment of access control attributes, you can use @property
decorator, @property
decorator is responsible for the property to become a method call
#!/usr/bin/env python3
class Account(object):
"""账号类,
amount 是美元金额.
"""
def __init__(self, rate):
self.__amt = 0
self.rate = rate
@property
def amount(self):
"""账号余额(美元)"""
return self.__amt
@property
def cny(self):
"""账号余额(人民币)"""
return self.__amt * self.rate
@amount.setter
def amount(self, value):
if value < 0:
print("Sorry, no negative amount in the account.")
return
self.__amt = value
if __name__ == '__main__':
acc = Account(rate=6.6) # 基于课程编写时的汇率
acc.amount = 20
print("Dollar amount:", acc.amount)
print("In CNY:", acc.cny)
acc.amount = -100
print("Dollar amount:", acc.amount)