Home Backend Development Python Tutorial 举例讲解Python面相对象编程中对象的属性与类的方法

举例讲解Python面相对象编程中对象的属性与类的方法

Jun 10, 2016 pm 03:06 PM
python object method kind

python 对象的属性
进入正题,来看一个实例来了解python中类,对象中公有属性,私有属性及局部变量,全局变量的区别.

root@10.1.6.200:~# cat object.py 
Copy after login

#!/usr/bin/env python
#coding:utf8
 
class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
 
  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
   
  def other(self):
    print self.__var3

Copy after login

根据上面代码后面加入以下代码可以实例化一个对象及获取类公有属性.

he = Dave()    #实例化一个对象he
print he.var1   #从实例中获取类的公有属性
print Dave.var1  #直接从类中获取公有属性

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

class atribute,public atrribute var1
class atribute,public atrribute var1
Copy after login

类的私有属性不能被类或对象直接调用

he = Dave()
print Dave.__var2
print he.__var2

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Traceback (most recent call last):
 File "./object.py", line 19, in <module>
  print Dave.__var2
AttributeError: class Dave has no attribute '__var2'
Copy after login

但可以通过方法间接调用.

class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
   
  def other(self):
    print Dave.__var2   
 
he = Dave()
he.other()

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

class self atribute __var2
Copy after login

获取类方法中的对象的公有属性,需要先通过对象执行类中的方法.并通过对象调用该属性.

he = Dave()
liu = Dave()
he.fun()
print he.var2
print liu.var2

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

object public atrribute var2
Traceback (most recent call last): <span></span>       #对象liu由于没有调用fun方法所有就没有该属性.
File "./object.py", line 20, in <module>
  print liu.var2
AttributeError: Dave instance has no attribute 'var2'
Copy after login

对象的私有属性和类的私有属性类似,也不能被类或对象直接调用

he = Dave()
he.fun()
print he.__var3

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Traceback (most recent call last):
 File "./object.py", line 18, in <module>
  print he.__var3
AttributeError: Dave instance has no attribute '__var3'

Copy after login

局部变量也不能被对象直接调用,可以在函数内部使用.

he = Dave()
he.fun()
print he.var4

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login


Traceback (most recent call last):
 File "./object.py", line 18, in <module>
  print he.var4
AttributeError: Dave instance has no attribute 'var4'

Copy after login

  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4       #可以在函数内部直接打印,只在该函数内有用
    print self.__var3
 
he = Dave()
he.fun()

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Function of the local variable var4
object self atrribute __var3
Copy after login

那么var4和self._var3有什么区别呢.目前看2个都在外部使用不了.下面在定义一个函数other调用.

  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4       #一个函数的局部变量在另外一个函数是访问不到的
    print self.__var3
   
  def other(self):
    print var4
    print self.__var3
 
he = Dave()
he.fun()
print "#"*100
he.other()

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Function of the local variable var4
object self atrribute __var3
####################################################################################################
Traceback (most recent call last):   #会认为var4是全局变量打印.定义全局变量可在class 头加入 var4 = "global"
 File "./object.py", line 22, in <module>
  he.other()
 File "./object.py", line 16, in other
  print var4
NameError: global name 'var4' is not defined

Copy after login

#!/usr/bin/env python
#coding:utf8
var4 = "global"            #定义var4为全局变量
class Dave():
  var1 = "class atribute,public atrribute var1" #类属性,公有属性var1
  __var2 = "class self atribute __var2"  #类的私有属性__var2
 
  def fun(self):
    self.var2 = "object public atrribute var2" #对象的公有属性var2
    self.__var3 = "object self atrribute __var3" #对象的私有属性__var3
    var4 = "Function of the local variable var4" #函数fun的局部变量
    print var4
    print self.__var3
   
  def other(self):
    print var4
    print self.__var3       #可调用私有属性,前提是先调用fun
 
he = Dave()
he.fun()
print "#"*100
he.other()

Copy after login

root@10.1.6.200:~# ./object.py 
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

Function of the local variable var4
object self atrribute __var3
####################################################################################################
global
object self atrribute __var3

Copy after login

python 类的方法
python类中的方法:公有方法,私有方法,类方法,静态方法.

下面通过一个实例了解它们之间的区别:

#!/usr/bin/env python
#coding:utf8
class Dave():
  name = "python"
 
  def fun1(self):        #定义公有方法
    print self.name
    print "i am public method"
 
  def __fun2(self):       #定义私有方法
    print self.name
    print "i am self method"
Copy after login

先来看公有方法和私有方法,加入以下代码输出

root@10.1.6.200:~# ./method.py    #直接调用对象公有方法没有问题

Copy after login

python
i am public method
Copy after login

私有方法和私有属性一样是被保护起来,不能直接调用对象的私有方法,但可以间接调用.

#!/usr/bin/env python
#coding:utf8
class Dave():
  name = "python"
 
  def fun1(self):        #定义公有方法
    print self.name
    print "i am public method"
    self.__fun2()
 
  def __fun2(self):       #定义私有方法
    print self.name
    print "i am self method"
 
he = Dave()
he.fun1()

Copy after login

root@10.1.6.200:~# ./method.py 
Copy after login
Copy after login
Copy after login
Copy after login

python
i am public method
python
i am self method

Copy after login

公有属性是可以被类调用,但是公有方法是不可以被类直接调用.需要实例化对象调用.如果想一个方法被类直接调用的话,就需要转换,变成一个类方法.变成类方法有2种,比较简单的可以加装饰器.

  @classmethod
  def classFun(self):      #定义类方法
    print self.name
    print "i am class method"
 
Dave.classFun()

Copy after login

root@10.1.6.200:~# ./method.py 
Copy after login
Copy after login
Copy after login
Copy after login

python
i am class method
Copy after login

另一个方法比较麻烦,需要定义一个新的函数,以及使用classmethod方法转换函数为类方法.当然调用也需要使用新的该函数名字.

  def classFun(self):      #定义类方法
    print self.name
    print "i am class method"
 
  classnewFun = classmethod(classFun)
 
 
Dave.classnewFun()       #被转换后的是一个类方法,原来classfun还是一个普通方法

Copy after login

root@10.1.6.200:~# ./method.py 
Copy after login
Copy after login
Copy after login
Copy after login

python
i am class method

Copy after login

静态方法在使用中和类方法一样,也是为了让类中直接调用,区别定义时不加self.

  @staticmethod
  def staticFun():       #d定义静态方法
    print Dave.name #注意不加self,直接打name也不行,会认为调用全局变量,需要使用类型加属性.
    print "i am static method"
 
Dave.staticFun()
Copy after login

oot@10.1.6.200:~# ./method.py 
Copy after login

python
i am static method
Copy after login
Copy after login

同样也可以通过一个函数调用

  def staticfun():       #定义静态方法
    print Dave.name
    print "i am static method"
 
  staticnewFun = staticmethod(staticFun)
 
Dave.staticnewFun()

Copy after login

root@10.1.6.200:~# ./method.py 
Copy after login
Copy after login
Copy after login
Copy after login

python
i am static method
Copy after login
Copy after login
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

HadiDB: A lightweight, horizontally scalable database in Python HadiDB: A lightweight, horizontally scalable database in Python Apr 08, 2025 pm 06:12 PM

HadiDB: A lightweight, high-level scalable Python database HadiDB (hadidb) is a lightweight database written in Python, with a high level of scalability. Install HadiDB using pip installation: pipinstallhadidb User Management Create user: createuser() method to create a new user. The authentication() method authenticates the user's identity. fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to use AWS Glue crawler with Amazon Athena How to use AWS Glue crawler with Amazon Athena Apr 09, 2025 pm 03:09 PM

As a data professional, you need to process large amounts of data from various sources. This can pose challenges to data management and analysis. Fortunately, two AWS services can help: AWS Glue and Amazon Athena.

How to start the server with redis How to start the server with redis Apr 10, 2025 pm 08:12 PM

The steps to start a Redis server include: Install Redis according to the operating system. Start the Redis service via redis-server (Linux/macOS) or redis-server.exe (Windows). Use the redis-cli ping (Linux/macOS) or redis-cli.exe ping (Windows) command to check the service status. Use a Redis client, such as redis-cli, Python, or Node.js, to access the server.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

See all articles