Doot
Doot

Reputation: 745

How is it possible that a Python built-in data type can have attributes that have the same data type?

Obviously this cannot be done in Python code, such as

class Foo:
    a = Foo()

but how did they manage to program this when creating the language itself?

Examples include int having the attributes real, imag, numerator and denominator; str having __doc__; methods having their own methods and type being its own meta class.

How could they get around the recursion caused if you tried to replicate something like this using Python code?

Upvotes: 0

Views: 59

Answers (2)

Torxed
Torxed

Reputation: 23490

Not sure if this is along the lines of what you need to achieve.
But a neat workaround might be to use @property decorators?

class Foo:

    @property
    def a(self):
        return Foo()

x = Foo()
print(x)
print(x.a)
print(type(x) == type(x.a) == Foo)


<__main__.Foo object at 0x033083B8>
<__main__.Foo object at 0x033081D8>
True

Technically this gets you around the recursion. It strictly speaking won't create the second instance immediately, so if that's a factor you need to take into consideration neither mine or Amitai's answers will do that for you. But it will create a property on instance creation called a but won't do anything until you access it.

Upvotes: 1

Amitai Irron
Amitai Irron

Reputation: 2055

Well, your assumption is not exactly true. You can assign to class members after the class has been created. Consider the following:

# Class definition
class Foo:

    foo = None

    def the_foo(self):
        return Foo.foo

# Assigning to the class member
Foo.foo = Foo()

# Creating an object and accessing class member through an object method
a_foo = Foo()
print("type(a_foo.the_foo()) =", type(a_foo.the_foo()))

This yields:

type(a_foo.the_foo()) = <class '__main__.Foo'>

So, if this can be done in Python, why not in built-in classes?

Upvotes: 3

Related Questions