search
HomeBackend DevelopmentPython TutorialIntroduction to public properties of classes
Introduction to public properties of classesJul 17, 2017 pm 03:58 PM
Publicly ownedAttributes

1. Concept

We mentioned earlier the private attributes of the class, which are those that cannot be directly accessed in the class. But what if properties that can be directly accessed are public properties? Not really. The properties in the __init__() constructor are basically accessible to the outside world, but they are not public properties. So what are public attributes?

Definition: Refers to properties that can be accessed by all objects belonging to this class, called public properties.

2. Attributes

2.1 Member attributes

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('Bigberg', 'Doctor', '8833421', 'hz')
p2 = Person('Ashlex', 'Police', '8833232', 'bj')
print(p1.job, p2.job)

# 输出
Doctor Police

We defined them under the Person class Two objects, p1 and p2. Obviously we have no way for p1 to access the job attribute of p2, that is, Police. Then attributes such as self.name in the constructor __init__() are called member attributes.

2.2 Public properties

class Person(object):
    nationality = 'CN'   # 定义公有属性

    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')
p2 = Person('Ashlex', 'Police', '8833232', 'bj')

print(p1.nationality)
print(p2.nationality)

# 输出

CN
CN

For public properties, the values ​​obtained by all instance objects accessing them are the same. .

3. Characteristics of public attributes

We can not only access, but also change public attributes.  

class Person(object):
    nationality = 'CN'   # 定义公有属性

    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')
p2 = Person('Ashlex', 'Police', '8833232', 'bj')

print(Person.nationality)  # 调用 公有属性
Person.nationality = 'us'   # 改变 公有属性
print(Person.nationality)

#输出

CN 
us

 

3.1 Single instance call and change public properties

# 依据上例

print("--------Befoer change---------")
print(Person.nationality)
print(p1.nationality)
print(p2.nationality)

print("--------after change---------")
print(Person.nationality)
p1.nationality = 'JP'
print(p1.nationality)
print(p2.nationality)


# 输出

---- ----Befoer change---------
CN
CN
CN
--------after change---------
US
JP
US

We can understand p1 very well before modification, because everyone is calling the public attribute nationality of class Person, so the nationality attributes of p1 and p2 They are the same, both are 'CN'. But why did the nationality attribute of p2 not change after p1 modified the public attribute?

 

When we define a Person class, it actually already exists in the memory. , of course also contains the public properties of this class. When the initial instance p1 calls the nationality attribute of class Person, it directly refers to the memory address of nationality in the class instead of adding a new attribute called nationality.

As shown below:

print(id(Person.nationality))
print(id(p1.nationality))
print(id(p2.nationality))
print(Person.nationality, p1.nationality, p2.nationality)

#输出
1751236836128
1751236836128
1751236836128
CN CN CN

This can explain why p2 also changes when the nationality in the Person class is changed to 'US'. Because it directly references the value in memory.

 

p1.nationality = 'JP'

After p1 directly assigns the nationality attribute, instance p1 actually adds a new member variable to itself, called nationality. It's just that their names are the same, but there is no connection between the two, and even the memory addresses are different.

# p1.nationality = 'JP'
print(id(Person.nationality))
print(id(p1.nationality))
print(id(p2.nationality))
print(Person.nationality, p1.nationality, p2.nationality)

#输出
2434579585096
2434579585152
2434579585096
US JP US

Therefore, p1.nationality='JP' does not modify the public attributes of class Person, but creates a new member attribute for itself. Therefore, the change of p1 has an impact on the class. Public properties have no effect.

The above is the detailed content of Introduction to public properties of 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
如何在Java中使用Gson重命名JSON的属性?如何在Java中使用Gson重命名JSON的属性?Aug 27, 2023 pm 02:01 PM

Gson@SerializedName注释可以序列化为JSON,并将提供的名称值作为其字段名称。此注释可以覆盖任何FieldNamingPolicy,包括可能已在Gson实例上设置的默认字段命名策略。可以使用GsonBuilder类设置不同的命名策略。语法@Retention(value=RUNTIME)@Target(value={FIELD,METHOD})public@interfaceSerializedName示例importcom.google.gson.annotations.*;

如何在Python中获取整数字面量属性而不是SyntaxError?如何在Python中获取整数字面量属性而不是SyntaxError?Aug 20, 2023 pm 07:13 PM

TogetintliteralattributeinsteadofSyntaxError,useaspaceorparenthesis.TheintliteralisapartifNumericLiteralsinPython.NumericLiteralsalsoincludesthefollowingfourdifferentnumericaltypes−int(signedintegers)−Theyareoftencalledjustintegersorints,arepositiveo

Python的dir()函数:查看对象的属性和方法Python的dir()函数:查看对象的属性和方法Nov 18, 2023 pm 01:45 PM

Python的dir()函数:查看对象的属性和方法,需要具体代码示例摘要:Python是一种强大而灵活的编程语言,其内置函数和工具为开发人员提供了许多方便的功能。其中一个非常有用的函数是dir()函数,它允许我们查看一个对象的属性和方法。本文将介绍dir()函数的用法,并通过具体的代码示例来演示其功能和用途。正文:Python的dir()函数是一个内置函数,

Win11磁盘属性未知怎么办Win11磁盘属性未知怎么办Jul 03, 2023 pm 04:17 PM

  Win11磁盘属性未知怎么办?近期Win11用户在电脑的使用中,发现系统出现提示磁盘错误的情况,这是怎么回事儿呢?而且应该如何解决呢?很多小伙伴不知道怎么详细操作,小编下面整理了Win11磁盘出错的解决步骤,如果你感兴趣的话,跟着小编一起往下看看吧!  Win11磁盘出错的解决步骤  1、首先,按键盘上的Win+E组合键,或点击任务栏上的文件资源管理器;  2、文件资源管理器的右侧边栏,找到边右键点击本地磁盘(C:),在打开的菜单项中,选择属性;  3、本地磁盘(C:)属性窗口,切换到工具选

pageXOffset属性在JavaScript中的作用是什么?pageXOffset属性在JavaScript中的作用是什么?Sep 16, 2023 am 09:17 AM

如果您想获取文档从窗口左上角滚动到的像素,请使用pageXoffset和pageYoffset属性。对水平像素使用pageXoffset。示例您可以尝试运行以下代码来了解如何在JavaScript中使用pageXOffset属性-现场演示<!DOCTYPEhtml><html>&nbsp;&nbsp;<head>&nbsp;&nbsp;&nbsp;<style>&nbsp;&nbsp;&

使用Vue.set函数实现动态添加属性的方法和示例使用Vue.set函数实现动态添加属性的方法和示例Jul 24, 2023 pm 07:22 PM

使用Vue.set函数实现动态添加属性的方法和示例在Vue中,如果我们想要动态地添加一个属性到一个已经存在的对象上,通常会使用Vue.set函数来实现。Vue.set函数是Vue.js提供的一个全局方法,它能够在添加属性时保证响应式更新。本文将介绍Vue.set的使用方法,并提供一个具体的示例。首先,在Vue中,我们通常会使用data选项来声明响应式的数据。

position有哪些属性position有哪些属性Oct 10, 2023 am 11:18 AM

position属性取值有static、relative、absolute、fixed和sticky等。详细介绍:1、static是position属性的默认值,表示元素按照正常的文档流进行布局,不进行特殊的定位,元素的位置由其在HTML文档中的先后顺序决定,无法通过top、right、bottom和left属性进行调整;2、relative是相对定位等等。

电脑双击文件夹打开的是属性怎么办电脑双击文件夹打开的是属性怎么办Jan 01, 2021 pm 04:04 PM

电脑双击文件夹打开的是属性的解决方法:1、打开控制面板,进入“轻松使用”选项;2、点击“轻松使用设置中心”下方的更改键盘工作方式选项;3、取消勾选使用粘滞键,点击“应用”即可。

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尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.