MarkK
MarkK

Reputation: 1088

In Python how to pass and set the same properties from one class to another

I have a class User with a number of properties. I wan to pass 'some' of same properties on the client object and allow them to all be accessed as follows:

User(x=1)
User.x
User.y
User.client.x

This is what I have tried, but cannot get it to work. TypeError: __init__() takes 1 positional argument but 2 were given.

class User(object):

    def __init__(self, x, y etc...):

        self.x = x
        self.y = y
        # objects

        self.client = Client(self)

    @property
    def z(self):
        return "test"

class Client(object):

    def __init__(self, **kwargs):

        self.x = kwargs.get('x')

Upvotes: 0

Views: 59

Answers (4)

TwistedSim
TwistedSim

Reputation: 2040

Also, if you want to access any attribute of user from the client, you can use this. But imust say, I don't know how this can be useful for you:

class User:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.client = Client(self)


class Client:
    def __init__(self, user):
        self.user = user
        self.z = 10
    def __getattr__(self, item):
        __no_attr_marker = object()  # allow a None in a User attribute
        user_item = getattr(self.user, item, __no_attr_marker)
        if user_item is not __no_attr_marker:
            return user_item
        else:
            return self.__getattribute__(item)

testing:

user = User(1, None)
print(user.x)
print(user.y)
print(user.client.x)
print(user.client.z)
print(user.client.client)

1
None
1
10
<__main__.Client object at 0x7f4e904bf8d0>

Upvotes: 1

shahaf
shahaf

Reputation: 4983

this is also a way

class User(object):

    def __init__(self, x):
        self.x = x
        self.client = Client(self)


class Client(object):

    def __init__(self, user):
        self.user = user

    @property
    def x(self):
        return self.user.x


u = User(1)
print u.x
u.x = 3
print u.client.x

output

1
3

Upvotes: 1

TwistedSim
TwistedSim

Reputation: 2040

Your test are using User in a wrong way. you need to keep the object return by the User class:

user = User(1, 2)
print(user.x)
print(user.y)
print(user.client.x)

Upvotes: 0

fferri
fferri

Reputation: 18950

The constructor of client takes 0 positional arguments. You should add one positional argument for the instance of the User class. And you don't really need the **kwargs.

class Client(object):

    def __init__(self, parent):

        self.x = parent.x

Upvotes: 1

Related Questions