Empty class object in Python

后端 未结 4 1767
情深已故
情深已故 2020-12-15 02:31

I\'m teaching a Python class on object-oriented programming and as I\'m brushing up on how to explain classes, I saw an empty class definition:

class Employe         


        
相关标签:
4条回答
  • 2020-12-15 03:04

    A class is more or less a fancy wrapper for a dict of attributes to objects. When you instantiate a class you can assign to its attributes, and those will be stored in foo.__dict__; likewise, you can look in foo.__dict__ for any attributes you have already written.

    This means you can do some neat dynamic things like:

    class Employee: pass
    def foo(self): pass
    Employee.foo = foo
    

    as well as assigning to a particular instance. (EDIT: added self parameter)

    0 讨论(0)
  • 2020-12-15 03:13

    Try with lambda:

    john.greet = lambda : print( 'hello world!' )
    

    The you'll be able to do:

    john.greet()
    

    EDIT: Thanks Thomas K for the note - this works on Python 3.2 and not for Python2, where print appeared to be statement. But this will work for lambdas, without statements (right? Sorry, I know only python3.2 (: )

    0 讨论(0)
  • 2020-12-15 03:16

    You could also use "named tuples" from the collection standard module. Named tuples work like "ordinary" tuples but the elements have names and you can access the elements using the "dot syntax". From the collection docs:

    >>> # Basic example
    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
    >>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
    33
    >>> x, y = p                # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y               # fields also accessible by name
    33
    >>> p                       # readable __repr__ with a name=value style
    Point(x=11, y=22)
    
    0 讨论(0)
  • 2020-12-15 03:21

    You could use AttrDict

    >>> from attrdict import AttrDict
    >>> my_object = AttrDict()
    >>> my_object.my_attribute = 'blah'
    >>> print my_object.my_attribute
    blah
    >>> 
    

    Install attrdict from PyPI:

    pip install attrdict 
    

    It's useful in other situations too - like when you need attribute access to dict keys.

    0 讨论(0)
提交回复
热议问题