Home  >  Article  >  Backend Development  >  Detailed explanation of attributes, methods, encapsulation, and inheritance based on python3 classes

Detailed explanation of attributes, methods, encapsulation, and inheritance based on python3 classes

巴扎黑
巴扎黑Original
2017-09-21 10:49:582547browse

The following editor will bring you an example explanation of attributes, methods, encapsulation, and inheritance based on python3 classes. The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

Python classes

Classes in Python provide all the basic functions of object-oriented programming: classes The inheritance mechanism allows multiple base classes. A derived class can override any method in the base class, and the method can call the method of the same name in the base class.

Objects can contain any amount and type of data.

Python classes are similar to C++ classes, providing class encapsulation, inheritance, multiple inheritance, constructors, and destructors.

In python3, the top-level parent class of all classes is the object class. Similar to Java, if the parent class is not written when defining the class, the object class is its direct parent class.

Class definition

The syntax format of class definition is as follows:


class ClassName:
<statement-1>
.
.
.
<statement-N>

Class object : After creating a class, you can access and change its properties and methods through the class name

Instance object: After the class is instantiated, you can use its properties, and you can dynamically add properties to the instance object (similar to javascript) without Influence class objects.

Attributes of the class

You can use dot (.) to access the properties of the object

You can also use the following functions Ways to access attributes:

getattr(obj, name[, default]): Access the attributes of the object

hasattr(obj,name): Check whether an attribute exists

setattr(obj,name,value): Set an attribute. If the attribute does not exist, a new attribute will be created

delattr(obj, name): Delete attribute

Python built-in class attribute

__dict__: Attributes of the class (contains a dictionary consisting of data attributes of the class)

__doc__: Documentation string of the class

__name__: Class name

__module__ : The module where the class definition is located (the full name of the class is '__main__.className', if the class is located in an imported module mymod, then className.__module__ is equal to mymod)

__bases__ : All parent class elements of the class ( Contains a tuple consisting of all parent classes)


class Person:
  "Person类"
  def __init__(self, name, age, gender):
    print(&#39;进入Person的初始化&#39;)
    self.name = name
    self.age = age
    self.gender = gender
    print(&#39;离开Person的初始化&#39;)
  def getName(self):
    print(self.name)
p = Person(&#39;ice&#39;, 18, &#39;男&#39;)
print(p.name) # ice
print(p.age) # 18
print(p.gender) # 男
print(hasattr(p, &#39;weight&#39;)) # False
# 为p添加weight属性
p.weight = &#39;70kg&#39;
print(hasattr(p, &#39;weight&#39;)) # True
print(getattr(p, &#39;name&#39;)) # ice
print(p.__dict__) # {&#39;age&#39;: 18, &#39;gender&#39;: &#39;男&#39;, &#39;name&#39;: &#39;ice&#39;}
print(Person.__name__) # Person
print(Person.__doc__) # Person类
print(Person.__dict__) # {&#39;__doc__&#39;: &#39;Person类&#39;, &#39;__weakref__&#39;: <attribute &#39;__weakref__&#39; of &#39;Person&#39; objects>, &#39;__init__&#39;: <function Person.__init__ at 0x000000000284E950>, &#39;getName&#39;: <function Person.getName at 0x000000000284EA60>, &#39;__dict__&#39;: <attribute &#39;__dict__&#39; of &#39;Person&#39; objects>, &#39;__module__&#39;: &#39;__main__&#39;}
print(Person.__mro__) # (<class &#39;__main__.Person&#39;>, <class &#39;object&#39;>)
print(Person.__bases__) # (<class &#39;object&#39;>,)
print(Person.__module__) # __main__

methods

Within a class, you can use the def keyword to define a method for the class. Unlike general function definitions, class methods must contain the parameter self, which is the first parameter.

Proprietary methods of the class:

__init__ constructor, which is called when generating the object.

__del__ destructor, which is used when releasing the object.

__repr__ Print, convert

__setitem__ Assign value according to index

__getitem__ Get value according to index

__len__ Get length

__cmp__ Compare Operation

__call__function call

__add__addition operation

__sub__subtraction operation

__mul__multiplication operation

__p__division Operation

__mod__Remainder operation

__pow__Weighing square

__init__() method is a special method, which is called the constructor or initialization method of a class. This method is called when an instance of this class is created, similar to the constructor in C++. Just override the __init__() method in your custom class.


class Person:
  def __init__(self, name, age, gender):
    print(&#39;进入Person的初始化&#39;)
    self.name = name
    self.age = age
    self.gender = gender
    print(&#39;离开Person的初始化&#39;)
  def getName(self):
    print(self.name)
# Person实例对象
p = Person(&#39;ice&#39;, 18, &#39;男&#39;)
print(p.name)
print(p.age)
print(p.gender)
p.getName()
# 进入Person的初始化
# 离开Person的初始化
# ice
# 18
# 男
# ice

Destructor __del__, __del__ is called when the object disappears. When the object is no longer used, the __del__ method runs:

Method

Instance method: can only be called through the instance. The first defined parameter of the instance method can only be a reference to the instance itself


class Myclass:
  def foo(self):
    print(id(self),&#39;foo&#39;)

a=Myclass()#既然是实例对象,那就要创建实例
a.foo()#输出类里的函数地址
print(id(a))#输出类对象的地址

#结果地址一样

Class method: To define a class method, use the decorator @classmethod. The first parameter defined can be a reference to the class object, which can be used directly through the class or instance


class Myclass:
@classmethod#类装饰器
  def foo2(cls):
    print(id(cls),&#39;foo2&#39;)
  #类对象,直接可以调用,不需要实例化
print(id(Myclass),&#39;yy&#39;)
Myclass.foo2()#直接可以调用

Static method: Define a static method using the decorator @staticmethod. There are no default required parameters and can be called directly through classes and instances.


class Myclass:
@staticmethod#静态方法
  def foo3():
    print(&#39;foo3&#39;)

Myclass.foo3()#没有参数
a.foo3()
#结果foo3

Encapsulation of classes

Python uses variable names to distinguish the access permissions of attributes and methods. The default permissions are equivalent to public
## in c++ and java

#Private attributes of the class: __private_attrs: Starting with two underscores, it is declared that the attribute is private and cannot be used or directly accessed outside the class. When using self.__private_attrs in a method inside a class.

Private methods of the class: __private_method: Starting with two underscores, it is declared that the method is a private method and cannot be called outside the class. Calling self.__private_methods inside a class


While Python does not allow instantiated classes to access private data, attributes can be accessed using object._className__attrName. In fact, the implementation of python's internal privatization only changes the attrName attribute to _className__attrName.


class Demo:
  __id = 123456
  def getId(self):
    return self.__id
temp = Demo()
# print(temp.__id) # 报错 AttributeError: &#39;Demo&#39; object has no attribute &#39;__id&#39;
print(temp.getId()) # 123456
print(temp._Demo__id) # 123456

Inheritance of class

One of the main benefits of object-oriented programming is the reuse of code, and one of the ways to achieve this reuse is through the inheritance mechanism. Inheritance can be completely understood as the type and subtype relationship between classes.

需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。

在python中继承中的一些特点:

1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。使用super().__init__()或parentClassName.__init__()

2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数

3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。

语法:

派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后。

多态

如果父类方法的功能不能满足需求,可以在子类重写父类的方法。实例对象调用方法时会调用其对应子类的重写后的方法

python3.3 类与继承 小例

hon中的类提供了面向对象编程的所有基本功能:类的继承机制允许多个基类,派生类可以覆盖基类中的任何方法,方法中可以调用基类中的同名方法。


class Base:
  def __init__(self):
    self.data=[]
  def add(self,x):
    self.data.append(x)
  def addtwice(self,x):
    self.add(x)
    self.add(x)

# child extends base
class Child(Base):
  def plus(self,a,b):
    return a+b

oChild=Child()
oChild.add("str1")
oChild.add(999)
oChild.addtwice(4)
print(oChild.data)
print(oChild.plus(2,3))

对象可以包含任意数量和类型的数据。

python类与c++类相似,提供了类的封装,继承、多继承,构造函数、析构函数。

在python3中,所有类最顶层父类都是object类,与java类似,如果定义类的时候没有写出父类,则object类就是其直接父类。

类定义

类定义语法格式如下:


class ClassName:
<statement-1>
.
.
.
<statement-N>

类对象:创建一个类之后,可以通过类名访问、改变其属性、方法

实例对象:类实例化后,可以使用其属性,可以动态的为实例对象添加属性(类似javascript)而不影响类对象。

类的属性

可以使用点(.)来访问对象的属性

也可以使用以下函数的方式来访问属性:

getattr(obj, name[, default]) : 访问对象的属性

hasattr(obj,name) : 检查是否存在一个属性
setattr(obj,name,value) : 设置一个属性。如果属性不存在,会创建一个新属性

delattr(obj, name) : 删除属性

Python内置类属性

__dict__ : 类的属性(包含一个字典,由类的数据属性组成)

__doc__ :类的文档字符串

__name__: 类名

__module__: 类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)

__bases__ : 类的所有父类构成元素(包含了以个由所有父类组成的元组)


class Person:
  "Person类"
  def __init__(self, name, age, gender):
    print(&#39;进入Person的初始化&#39;)
    self.name = name
    self.age = age
    self.gender = gender
    print(&#39;离开Person的初始化&#39;)
  def getName(self):
    print(self.name)
p = Person(&#39;ice&#39;, 18, &#39;男&#39;)
print(p.name) # ice
print(p.age) # 18
print(p.gender) # 男
print(hasattr(p, &#39;weight&#39;)) # False
# 为p添加weight属性
p.weight = &#39;70kg&#39;
print(hasattr(p, &#39;weight&#39;)) # True
print(getattr(p, &#39;name&#39;)) # ice
print(p.__dict__) # {&#39;age&#39;: 18, &#39;gender&#39;: &#39;男&#39;, &#39;name&#39;: &#39;ice&#39;}
print(Person.__name__) # Person
print(Person.__doc__) # Person类
print(Person.__dict__) # {&#39;__doc__&#39;: &#39;Person类&#39;, &#39;__weakref__&#39;: <attribute &#39;__weakref__&#39; of &#39;Person&#39; objects>, &#39;__init__&#39;: <function Person.__init__ at 0x000000000284E950>, &#39;getName&#39;: <function Person.getName at 0x000000000284EA60>, &#39;__dict__&#39;: <attribute &#39;__dict__&#39; of &#39;Person&#39; objects>, &#39;__module__&#39;: &#39;__main__&#39;}
print(Person.__mro__) # (<class &#39;__main__.Person&#39;>, <class &#39;object&#39;>)
print(Person.__bases__) # (<class &#39;object&#39;>,)
print(Person.__module__) # __main__

类的方法

在类地内部,使用def关键字可以为类定义一个方法,与一般函数定义不同,类方法必须包含参数self,且为第一个参数。

类的专有方法:

__init__ 构造函数,在生成对象时调用

__del__ 析构函数,释放对象时使用

__repr__ 打印,转换

__setitem__按照索引赋值

__getitem__按照索引获取值

__len__获得长度

__cmp__比较运算

__call__函数调用

__add__加运算

__sub__减运算

__mul__乘运算

__p__除运算

__mod__求余运算

__pow__称方

__init__()方法是一种特殊的方法,被称为类的构造函数或初始化方法,当创建了这个类的实例时就会调用该方法,与c++中构造函数类似。只需在自定义的类中重写__init__()方法即可。


class Person:
  def __init__(self, name, age, gender):
    print(&#39;进入Person的初始化&#39;)
    self.name = name
    self.age = age
    self.gender = gender
    print(&#39;离开Person的初始化&#39;)
  def getName(self):
    print(self.name)
# Person实例对象
p = Person(&#39;ice&#39;, 18, &#39;男&#39;)
print(p.name)
print(p.age)
print(p.gender)
p.getName()
# 进入Person的初始化
# 离开Person的初始化
# ice
# 18
# 男
# ice

析构函数 __del__ ,__del__在对象消逝的时候被调用,当对象不再被使用时,__del__方法运行:

类的封装

python通过变量名命名来区分属性和方法的访问权限,默认权限相当于c++和java中的public

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

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

虽然python不允许实例化的类访问私有数据,但可以使用 object._className__attrName 访问属性。其实python内部私有化的实现只是将attrName属性变为了_className__attrName而已


class Demo:
  __id = 123456
  def getId(self):
    return self.__id
temp = Demo()
# print(temp.__id) # 报错 AttributeError: &#39;Demo&#39; object has no attribute &#39;__id&#39;
print(temp.getId()) # 123456
print(temp._Demo__id) # 123456

类的继承

面向对象的编程带来的主要好处之一是代码的重用,实现这种重用的方法之一是通过继承机制。继承完全可以理解成类之间的类型和子类型关系。

需要注意的地方:继承语法 class 派生类名(基类名)://... 基类名写作括号里,基本类是在类定义的时候,在元组之中指明的。

在python中继承中的一些特点:

1:在继承中基类的构造(__init__()方法)不会被自动调用,它需要在其派生类的构造中亲自专门调用。使用super().__init__()或parentClassName.__init__()

2:在调用基类的方法时,需要加上基类的类名前缀,且需要带上self参数变量。区别于在类中调用普通函数时并不需要带上self参数

3:Python总是首先查找对应类型的方法,如果它不能在派生类中找到对应的方法,它才开始到基类中逐个查找。(先在本类中查找调用的方法,找不到才去基类中找)。

如果在继承元组中列了一个以上的类,那么它就被称作"多重继承" 。

语法:

派生类的声明,与他们的父类类似,继承的基类列表跟在类名之后。

多态

如果父类方法的功能不能满足需求,可以在子类重写父类的方法。实例对象调用方法时会调用其对应子类的重写后的方法

python3.3 类与继承 小例


class Base:
def __init__(self):
self.data=[]
def add(self,x):
self.data.append(x)
def addtwice(self,x):
self.add(x)
self.add(x)

# child extends base
class Child(Base):
def plus(self,a,b):
return a+b

oChild=Child()
oChild.add("str1")
oChild.add(999)
oChild.addtwice(4)
print(oChild.data)
print(oChild.plus(2,3))

The above is the detailed content of Detailed explanation of attributes, methods, encapsulation, and inheritance based on python3 classes. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:python basic syntaxNext article:python basic syntax