Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - Empty class object in Python

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 Employee:
    pass

The example then goes on to define a name and other attributes for an object of this class:

john = Employee()
john.full_name = "john doe"

Interesting!

I'm wondering if there's a way to dynamically define a function for an instance of a class like this? something like:

john.greet() = print 'Hello, World!'

This doesn't work in my Python interpreter, but is there another way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...