简体   繁体   English

Python class 和方法 - 访问和更改属性的最佳实践?

[英]Python class and methods - best practice for accessing and altering attributes?

TLDR: What's best practice for accessing and altering attributes of a class instance? TLDR:访问和更改 class 实例的属性的最佳做法是什么?

Let's say we have a class to generate an object that is intended to hold data about a product (eg maybe a product master dataset).假设我们有一个 class 来生成一个 object,该 object 旨在保存有关产品的数据(例如,可能是产品主数据集)。

class StoreProduct(object):

    def __init__(self,ProductID,ProductPrice,ProductDescription):
        self.ProductID = ProductID
        self.ProductPrice = ProductPrice
        self.ProductDescription = ProductDescription


    def ChangeProductPrice(self, newProductPrice):
        self.ProductPrice = newProductPrice

And we have another class we may be able to use to access those instances generated by StoreProduct(), with methods for making adjustments / changes.我们还有另一个 class,我们可以使用它来访问由 StoreProduct() 生成的那些实例,以及进行调整/更改的方法。

class ChangeProductData(object):

    def __init__(self):
        pass
    @staticmethod
    def ChangeProductObjectPrice(newProductPrice,ProductObject):

        ProductObject.ProductPrice = newProductPrice

So we generate an instance named Product1:所以我们生成一个名为 Product1 的实例:

Product1 = StoreProduct(
    ProductID="Product1",
    ProductPrice=4,
    ProductDescription="A nice lamp"
)

What's best practice coding for reading and/or altering class instances?读取和/或更改 class 实例的最佳实践编码是什么?

If I wanted to alter an attribute in Product 1 (in this case the price) is something like this acceptable in general, or is it bad code?如果我想改变产品 1 中的一个属性(在本例中是价格),这样的事情一般来说是可以接受的,还是它是错误的代码?

Method 1方法一

ChangeProductData().ChangeProductObjectPrice(8,Product1)

Or is this the preferred way to do it?或者这是首选的方式吗?

Method 2方法二

Product1.ChangeProductPrice(2)

When might there be exceptions?什么时候可能会有例外?

While the above are simplified situations, what I've currently read seems to indicate that Method 2 might be better practice.虽然以上是简化的情况,但我目前阅读的内容似乎表明方法 2 可能是更好的做法。 However, wouldn't Method 1 provide greater flexibility in future (eg if you need to change how a method works, or add new methods).但是,方法 1 是否会在将来提供更大的灵活性(例如,如果您需要更改方法的工作方式或添加新方法)。

I have also been reading into getattr() and setattr(), but people seem to be mixed on whether its better than using dot (eg Product1.ProductPrice to get the price).我也一直在阅读 getattr() 和 setattr(),但人们似乎对它是否比使用点更好(例如 Product1.ProductPrice 来获取价格)感到困惑。

Definitely method 2. As @user2357112 mentions, method 1 doesn't make sense.绝对是方法 2。正如 @user2357112 提到的,方法 1 没有意义。 As you rightly pointed out, this is a simple scenario and the pythonic way would be use property正如您正确指出的那样,这是一个简单的场景,pythonic 方式是使用property

class StoreProduct(object):  # minor: please notice the PEP styling
    def __init__(self, product_price):
        self._price = produce_price
        # other attributes, omitted for brevity

    @property
    def product_price(self):  # pythonic getter
        return self._price

    @product_price.setter
    def product_price(self, new_price):  # python setter
        # you could do any custom validation before setting
        self._price = new_price

Coming to the question of来到这个问题

I'm specifically tackling the issue of whether accessing and altering an class' attribute with another class is a big no-no.我正在专门解决使用另一个 class 访问和更改类属性是否是一个大禁忌的问题。

  • Accessing: Accessing is okay here.访问:这里访问是可以的。 In fact many design patterns that rely on composition heavily do this.事实上,许多严重依赖组合的设计模式都是这样做的。 eg, adapter , strategy , decorator , command etc patterns例如, adapterstrategydecoratorcommand等模式

  • Altering: You want the class owning the attribute to be in charge of "altering".改变:你想让拥有属性的class负责“改变”。 Foreign classes should only request to alter .外国班应该只要求改变

PS This is treading a bit along the lines of CQRS(Command Query Responsibility Segregation) pattern PS 这有点像 CQRS(命令查询责任分离)模式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM