社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

alxwrd

alxwrd 最近创建的主题
alxwrd 最近回复了
7 年前
回复了 alxwrd 创建的主题 » 为什么python中有属性类属性?

区别是因为当你定义一个 @property 在课堂上, 对象属性 成为类的属性。而当您针对 实例 你的班级(在你的 __init__ 方法),该属性仅针对该对象存在。如果您这样做,这可能会令人困惑:

>>> dir(LineItem)
['__class__', ..., '__weakref__', 'subtotal', 'weight']

>>> item = LineItem("an item", 3, 1.12)
>>> dir(item)
['__class__', ..., '__weakref__', 'description', 'price', 'subtotal', 'weight']

注意这两者 subtotal weight 作为属性存在于类中。

我认为还值得注意的是,当您定义一个类时,该类下的代码将被执行。这包括定义变量(然后成为类属性)、定义函数以及其他任何内容。

>>> import requests

>>> class KindOfJustANamespace:
...     text = requests.get("https://example.com").text
...     while True:
...         break
...     for x in range(2):
...         print(x)
...
0
1
>>> KindOfJustANamespace.text
'<!doctype html>\n<html>\n<head>\n    <title>Example Domain...'

@decorator 只是” syntactic sugar “。意义 @财产 如果函数与 function = property(function) . 这也适用于在类内部定义的函数,但现在该函数是类命名空间的一部分。

class TestClass:
    @property
    def foo(self):
        return "foo"
    # ^ is the same as:
    def bar(self):
         return "bar"
    bar = property(bar)

一个很好的解释 property 在python中可以找到: https://stackoverflow.com/a/17330273/7220776