Python - @property vs func() [closed]

ⅰ亾dé卋堺 提交于 2020-01-24 01:01:10

问题


It had always been my dream to use someclass.func instead of someclass.func(). I read about the @decorators. And now I ask:

Which way is better?

Way 1

class Main(object):

    def __init__(self):

        self.func()

    def func(self):

        print 'hi'

or...

Way 2

class Main(object):

    def __init__(self):

        self.func

    @property
    def func(self):

        print 'hi'

EDIT

Here is the code: http://randomgalaxy.com/stackoverflow/python-property-vs-func/term.py


回答1:


If func really prints values, then no, making it a property is not the right thing to do. Properties are—as the name suggest—values that are attached to the object. As such, a function with the @property decorator should only return a value and have otherwise no side-effects.




回答2:


Edit: after reading your actual code DEFINITELY Way 1

Most likely: Way 1

BUT it depends on what you're actually trying to do. This case you presented is way oversimplified.

Using the @property decorator is in my experience either a way to protect a class member (only allowing reads), A way to do some bookkeeping when a variable is set/read, or a way to provide access to a member-like function (ie, just returns a value you request even if it requires some extra computation to get that value). I personally like to use it for lazy evaluation




回答3:


Properties should be values. Not functions.
Example:

class Foo(object):
    def __init__(self, a, b):
        self.__a = a
        self.__b = b

    @property
    def a(self):
        return self.__a

    @property
    def b(self):
        return self.__b

In this example, values are private and you can't change them.

So it's a bad idea to do something else there? I mean in my script function changes my vars and calls another functions – Vik2015 45 secs ago

It's very bad style. You're not in ruby :)



来源:https://stackoverflow.com/questions/19438189/python-property-vs-func

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!