Home  >  Article  >  Backend Development  >  What are Python class attributes? How to access properties in Python?

What are Python class attributes? How to access properties in Python?

Tomorin
TomorinOriginal
2018-08-14 16:54:462955browse

Python class attribute is a function that comes with the language. This article will explain through example analysis what Python class function is, and how to use Python to access attributes .

1.Python class attributesare:

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

2.__doc__: Documentation string of the class

3.__name__: Class Name

4.__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)

5.__bases__: All parent class elements of the class (contains a tuple composed of all parent classes)

2.So how to go How about using Python to access attributes?

We can use the period . to access the properties of the object. Use the following class name to access class variables:

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Contact one and two, let’s give an example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 class Employee:   '所有员工的基类'
   empCount = 0
 
   def __init__(self, name, salary):      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
   def displayCount(self):   
     print "Total Employee %d" % Employee.empCount
 
   def displayEmployee(self):      
     print "Name : ", self.name,  ", Salary: ", self.salary
 print "Employee.__doc__:", Employee.__doc__
 print "Employee.__name__:", Employee.__name__
 print "Employee.__module__:", Employee.__module__
 print "Employee.__bases__:", Employee.__bases__
 print "Employee.__dict__:", Employee.__dict__

The output result of executing the above code is as follows:

Employee.__doc__: 所有员工的基类
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount': 
<function displayCount at 0x10a939c80>, &#39;empCount&#39;: 0, &#39;displayEmployee&#39;: 
<function displayEmployee at 0x10a93caa0>, &#39;__doc__&#39;: 
&#39;\xe6\x89\x80\xe6\x9c\x89\xe5\x91\x98\xe5\xb7\xa5\xe7\x9a\x84\xe5\x9f\xba\xe7\xb1\xbb&#39;, 
&#39;__init__&#39;: <function __init__ at 0x10a939578>}


The above is the detailed content of What are Python class attributes? How to access properties in Python?. 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