search
HomeBackend DevelopmentPython TutorialIntroduction to classes and attributes

Introduction to classes and attributes

Jul 21, 2017 pm 02:14 PM
characteristic

1. Overview

1. Definition class (class Dog(object)) --> Instantiation (d = Dog()) ---> Instance object ( d)

2. __init__() constructor

3. self.name = name class attributes and member variables

4. def say_hi() class method, Dynamic attributes

2. Accessing the attributes of the class

class Role(object):
    def __init__(self, name, role, weapon, life_value=100, money=15000):
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.money = money

    def shot(self):
        print("%s is shooting..." % self.name)

    def got_shot(self):
        print("ah...,%s got shot..." % self.name)

    def buy_gun(self, gun_name):
        print("%s just bought %s" % (self.name,gun_name))


r1 = Role('Alex', 'police', 'AK47')  # 生成一个角色
r2 = Role('Jack', 'terrorist', 'B22')   # 生成一个角色

 

 2.1 Accessing the attributes and methods of the class

We use the instance object.properties/methods to access

r1.shot()    #  调用shot 方法
r2.buy_gun('B13')  # 调用 buy_gun的方法并传参
print(r1.role)   # 打印类的属性

# 输出

Alex is shooting...
Jack just bought B13
police

 

 2.1 Modify the properties of the object

In the above example, we changed the weapon for the character r2, namely B22 --> B13. But in fact, when we call the weapon attributes of the character r2, we will find that his weapon has not changed:

r2.buy_gun('B13')
print(r2.weapon)

# 输出
Jack just bought B13
B22       # 可以发现武器依然是 B22

In fact, we can directly change the attributes of the object when purchasing the weapon:

def buy_gun(self, gun_name):
      print("%s just bought %s" % (self.name, gun_name))
      self.weapon = gun_name    # 在方法内改变属性



r2.buy_gun('B13')
print(r2.weapon)

#输出
Jack just bought B13
B13    # 可以发现武器已经改变

 

3. Private attributes

 3.1. Define private attributes

Class Once an attribute is defined as a private attribute, it cannot be called externally or modified at will. Private properties can only be used within the class.

class Person(object):

    def __init__(self, name, job, phone, address):
        self.name = name
        self.job = job
        self.phone = phone
        self.__address = address   # 定义一个私有属性

    def sayhi(self):
        print("hell,%s" % self.name)

p1 = Person('Bigberg', 'Doctor', '8833421', 'hz')
print(p1.name)
print(p1.__address)   # 访问私有属性

# 输出

Bigberg
  File "G:/python/untitled/study6/类的私有属性.py", line 17, in <module>
    print(p1.__address)
AttributeError: &#39;Person&#39; object has no attribute &#39;__address&#39;

The result of the operation is that access to the attribute name is passable, but an error is reported when directly accessing the private attribute self.__address. But if you use other methods, you can still access it.

 3.2. The get method accesses private properties

Private properties cannot be accessed directly from the outside, but they can be accessed inside the class, so we can Define a method to get private properties.

class Person(object):

    def __init__(self, name, job, phone, address):
        self.name = name
        self.job = job
        self.phone = phone
        self.__address = address

    def get_private(self):
        return self.__address

    def sayhi(self):
        print("hell,%s" % self.name)

p1 = Person(&#39;Bigberg&#39;, &#39;Doctor&#39;, &#39;8833421&#39;, &#39;hz&#39;)
res = p1.get_private()
print(res)

# 输出
hz

 

 3.3 Forced access to private properties

We can also force access to private properties through a method, even Modify the value of a private property. Method: object name._class name__attribute name.

class Person(object):

    def __init__(self, name, job, phone, address):
        self.name = name
        self.job = job
        self.phone = phone
        self.__address = address

    def get_private(self):
        return self.__address

    def sayhi(self):
        print("hell,%s" % self.name)

p1 = Person(&#39;Bigberg&#39;, &#39;Doctor&#39;, &#39;8833421&#39;, &#39;hz&#39;)

print(p1._Person__address)   # 访问私有属性

print("----change----")
p1._Person__address = &#39;BJ&#39;    # 修改私有属性
print(p1._Person__address)

#输出
hz
----change----
BJ

 

Classes are an important tool for simplifying and optimizing applications.
1. Inheritance: The ability of subclasses to inherit the characteristics of parent classes. It embodies and expands the sharing of object-oriented programming methods, allowing objects of the same type to share data and program code, improving program reusability. The parent class is a class that can be further defined to derive new classes, and the subclass is a new class established by using other classes as a starting point and defining more specific characteristics.
2. Polymorphism: Some related classes contain methods with the same name, but the content of the methods can be different. Which one to call is determined at runtime based on the class of the object. The same message can lead to different actions when received by different objects.
3. Abstraction: Extract the distinctive features of a class or object without processing other information about the class or object.

4. Summary

1. Define private attributes: self.__private_attr_name = private_attr_name

2. Mandatory Access private attributes: object name._class name__attribute name (d._dog__sex)

3. Provide external read-only interface access:

Def get_sex(self):

return self.__sex

The above is the detailed content of Introduction to classes and attributes. 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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 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.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 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 Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft